简体   繁体   中英

Do-while loop won't escape - Java

Does a do-while loop check a value before or after it has been incremented? I can't seem to make this do-while loop escape, and can't determine if that is the mistake I am making. The point of this loop is to take input from the user and when they hit 'X', I want the loop to end. Am I using the wrong type of loop, or perhaps an incorrect statement?

int i = 0, 
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];  
do{ 
    System.out.print("What is " + letter +"? ");
    coefficient[i] = keyboard.nextLine();
    i++;
    letter++;
    inputCount++;           
}while(coefficient[i] != "X");

Don't compare Strings using == . Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of

if (fu == "bar") {
  // do something
}

do,

if ("bar".equals(fu)) {
  // do something
}

or,

if ("bar".equalsIgnoreCase(fu)) {
  // do something
}  

Specifically in your case, I'd change

} while(coefficient[i] != "X");

to something like:

} while(!"X".equalsIgnoreCase(coefficient[i]));

And you've got another problem in your code in that you want to test the user input which you place into coefficient[i] , but then you promptly increment the i variable such that coefficient[i] no longer refers to the input.

So perhaps the test should instead be:

} while(!"X".equalsIgnoreCase(coefficient[i - 1]));

There is two problems here. First you shouldn't compare Strings using logical operators. Use .equals instead. For example:

coefficient[i].equals("X");

Secondly you are incrementing your array index counter before you check the while condition. So you actually need to subtract one from it to check if the most recently entered String was X.

See if using this will get it working:

coefficient[i-1].equals("X");

You're incrementing i between coefficient[i] = keyboard.nextLine(); and while(coefficient[i] != "X"); , so in the while check coefficient[i] is null, also use .equals to compare strings.

int i = 0, 
inputCount = 0;
char letter = 'a';
String[] coefficient = new String[MAX_LENGTH];  
do{ 
    System.out.print("What is " + letter +"? ");
    coefficient[i] = keyboard.nextLine();
    i++;
    letter++;
    inputCount++;           
}while(!coefficient[i-1].equals("X"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM