[英]Java: Incrementing a variable inside of a for loop
I am in a beginner Java class and for a project I need to count how many times a condition returns TRUE(correctGuess) or FALSE(incorrectGuess) with a loop inside of a loop. 我在初学者Java类中,对于一个项目,我需要计算一个条件在循环内部循环返回TRUE(correctGuess)或FALSE(incorrectGuess)的次数。 The problem that I'm having is that the variables being incremented within the inner loop do not hold their incremented value as the loop reiterates. 我遇到的问题是,内循环中递增的变量在循环重复时不会保持其递增的值。 Therefore, the outer while-loop's condition is never false. 因此,外部while循环的条件永远不会错误。 I'm really new to programming and I can't figure out the solution. 我是编程新手,我无法找到解决方案。 Thank you in advance for your time with this silly question and if there are any questions I would be happy do a better explanation. 在这个愚蠢的问题上提前感谢你的时间,如果有任何问题,我会很高兴做一个更好的解释。 The code looks like this: 代码如下所示:
int incorrectGuess = 0;
int correctGuess = 0;
while(incorrectGuess < 6 && correctGuess < WORD_LENGTH) {
//Gets the users first guess
System.out.print("Please guess a letter [A-Z]: ");
letterGuessed = keyboard.nextLine();
for (int i = 0; i < WORD_LENGTH; i++){
char value = wordLetterArray[i];
String letterArray_value = String.valueOf(value);
if(letterGuessed.equals(letterArray_value)){
++correctGuess;
}
else
System.out.println("Bad comparison!");
if(i == WORD_LENGTH)
++incorrectGuess;
}
}
Looks like you may need to redesign the whole algorithm, but I can tell you what your main issue is with this looping forever: 看起来你可能需要重新设计整个算法,但我可以告诉你这个循环永远的主要问题是什么:
// Seems legit
while(incorrectGuess < 6 && correctGuess < WORD_LENGTH) {
// Still seems legit
for (int i = 0; i < WORD_LENGTH; i++)
// Well, there's a problem, i will never be equal to word length
//because a condition of the for loop is i < WORD_LENGTH
if(i == WORD_LENGTH)
++incorrectGuess;
Again, I feel you need to redesign your whole algorithm, but if you want it to continue, just pull the incorrectGuess increment line out of the for loop. 同样,我觉得你需要重新设计你的整个算法,但是如果你想继续它,只需从for循环中取出不正确的Guess增量线。 This will give you the intended result: 这将为您提供预期的结果:
for (int i = 0; i < WORD_LENGTH; i++){
char value = wordLetterArray[i];
String letterArray_value = String.valueOf(value);
if(letterGuessed.equals(letterArray_value)){
++correctGuess;
}
else {
System.out.println("Bad comparison!");
}
}
incorrectGuess++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.