2017-08-08 51 views
0

我很难理解我的代码真的有什么问题。我不是一个很好的开发人员,我仍然在学习,所以所有的技巧都非常受欢迎! :)input.nextLine()带有一个while循环中的字符串

所以我正在做的是有一个while循环,检查用户是否给扫描仪一个特定的字母。如果有,则循环结束。如果不是,它会一直问这个问题。

我的代码如下:

Scanner userInput = new Scanner(System.in); 
String userAnswer = userInput.nextLine(); 
boolean isTrue = true; 

    while (isTrue){ 
     if (userAnswer.equals("e")){ 
      System.out.println("Wrong, try again"); 
      userInput.nextLine(); 
     } else if (userAnswer.equals("k")) { 
      System.out.println("That's right!"); 
      isTrue = false; 
      break; 
     }  
    } 

它的工作原理,有点。如果用户回答“k”作为第一个答案,它会打印出“That's right!”。然后打破循环。如果用户给出答案“e”作为第一个答案,它将打印出“错误,再试一次”,并给出一个新的行再次回答,但如果你然后写了正确的字母,这是“K”,它仍然打印出“错了,再试一次”循环,不会跳转到“else if”语句。

我该如何解决这个问题?提前致谢。

+0

您需要在循环内部处理扫描仪。否则,您不会读取用户写入的下一个字符。 –

+3

你需要使用'userAnswer = userInput.readLine()'或者你的答案不会改变。 –

回答

2

您需要的nextLine

userAnswer = userInput.nextLine(); 
3

你是不是分配用户输入返回值分配给循环中的userAnswer变量。

变化

userInput.nextLine(); 

userAnswer = userInput.nextLine(); 
5

你必须重新分配值:

while (isTrue){ 
    if (userAnswer.equals("e")){ 
     System.out.println("Wrong, try again"); 
     userAnswer = userInput.nextLine(); 
    } else if (userAnswer.equals("k")) { 
     System.out.println("That's right!"); 
     isTrue = false; 
    }  
} 
+0

不是没用,只是不必要... –

+0

@davidxxx也许。我已经将它删除了 – Jens

+0

嘿,就是这样,太棒了!非常感谢! :) – Grv21

0

字符串是Java API不可变对象。所以当你下次阅读时你必须重新分配价值。

public static void main(String[] args) { 
    Scanner userInput = new Scanner(System.in); 
    String userAnswer = userInput.nextLine(); 
    boolean isTrue = true; 
    while (isTrue) { 
     if (userAnswer.equals("e")) { 
      System.out.println("Wrong, try again"); 
      userAnswer = userInput.nextLine(); 
     } else if (userAnswer.equals("k")) { 
      System.out.println("That's right!"); 
      isTrue = false; 
      break; 
     } 
    } 
}