Ken Ken - 23 days ago 10
Java Question

Loop that will exit if i enter X or give error if i dont enter a INT

I am trying to create a loop with any means possible, I have tried many different ways but this as close as I have been able to get. I need it to tell the user to enter an integer or tell them to enter x to exit. If they enter X I need it to exit the loop. if they enter an INT it does the loop over. But if they enter any other character besides x it will give them an error message and go back to asking them for an INT.

do
{
System.out.print("Enter an integer(x to exit): ");
temp2 = scan.next();
if(temp2.equalsIgnoreCase("x"))
{
done = true;
}
if(temp2 != "x")
{
try
{
temp = Integer.parseInt(temp2);
square.add(temp);
}
catch (NumberFormatException ne)
{
System.out.println("*** Invalid Data Entry ***");
}
}
while(!done);


doing it this way it returns the error "* Invalid Data Entry *" when i enter x but i don't want that error to appear if i enter x, i just want it to exit.

Answer

A simple logic change to

 if(temp2.equalsIgnoreCase("x"))
 {
    done = true;
 }
 else {
    ....
 }