do while loop terminating to early
Hi all,
I am a newbie to programming and this is my first attempt to write a java program. I calculating the root of a integer that is supplied by the user, this then calls a method that does the calculation. The user is then prompted to either continue to calculate more root calculations or terminate the program, in this case the program provides a "Thank you for participating" message. This is done by either providing a "y" or "n"
Even if the user enters a "y" to continue, the loop terminates. This is the code that I have written:
Code :
import java.io.*;
public class root {
public static int calcRoot(int a)
{
// if (a != integer)
// throw new intErrorExecption("Input must be a integer");
return a=(int) Math.sqrt(a);
}
public static void main(String[] args) throws IOException
{
int tempInt=0;
String sCont;
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
// try
do
{
System.out.print("Enter integer: ");
System.out.flush();
tempInt=Integer.parseInt( stdin.readLine());
// }
// catch (intErrorExecption e)
// {
System.out.println("The square root of " +tempInt+ " is "+calcRoot(tempInt));
System.out.print("Do you want to continue? (y / n): ");
System.out.flush();
/* Code to check if the read line provided y or n, if y continue loop else
* exit loop and print "Thank you for participating"
*/
sCont=stdin.readLine();
if(sCont=="n")
{
break;
}
} while (sCont == "y"); //loop is terminated here even though variable sCont is set here for string value "y"
System.out.println("Thank you for participating");
}
}
I am greatfull if someones spots the error of my algorithm.
thanks
-Sohail
Re: do while loop terminating to early
Don't use == to compare Strings. Use the equals() method instead. The == operator determines whether two Objects are the same instance, the equals() method checks for semantic equality.
Re: do while loop terminating to early
Thanks a lot, I altered my conditional and looping code to the following and it worked:
Code :
do
{
System.out.print("Enter integer: ");
System.out.flush();
tempInt=Integer.parseInt( stdin.readLine());
System.out.println("The square root of " +tempInt+ " is "+calcRoot(tempInt));
System.out.print("Do you want to continue? (y / n): ");
System.out.flush();
/* Code to check if the read line provided y or n, if y continue loop else
* exit loop and print "Thank you for participating"
*/
sCont=stdin.readLine();
if(sCont.equals("n"))
{
break;
}
} while (sCont.equals("y"));
System.out.println("Thank you for participating");
Re: do while loop terminating to early
For Strings, you might also want to check out the equalsIgnoreCase() function.