Java 如何检查单个字符并中断循环

Java 如何检查单个字符并中断循环,java,Java,我有一个循环: String cont = ""; while ( cont != "n" ) { // Loop stuff System.out.print("another item (y/n)?"); cont = input.next(); } 然而,当我输入“n”停止循环时,它只是继续运行。怎么了?试试这个: while ( !cont.equals( "n" ) ) { 您需要使用equals(): 请改用.equals方法 String cont = ""; do { //

我有一个循环:

String cont = "";
while ( cont != "n" ) {
// Loop stuff

System.out.print("another item (y/n)?");
cont = input.next();
}
然而,当我输入“n”停止循环时,它只是继续运行。怎么了?

试试这个:

while ( !cont.equals( "n" ) ) {

您需要使用
equals()


请改用.equals方法

String cont = "";
do {
// Loop stuff

System.out.print("another item (y/n)?");
cont = input.next();
} while ( !"n".equals(cont) );

您正在比较对象而不是基本体。
字符串
是一个对象,
==
=不按“内部值”比较对象,而是按引用比较对象

您有两种选择:

  • 使用方法

  • 使用原语
    char
    而不是
    String

    char cont = 'y';
    while (cont != 'n') {
        // ...
        cont = input.next().charAt(0);
    }
    

  • @这是一个怎样的评论?@ColeJohnson说实话,我可以从任何一个角度来看待它。我个人倾向于喜欢解释的那一边。在这种情况下,它可能已经包括了一行为什么他们应该使用equals方法而不是
    =以比较方法。它为提问者提供了他们当前问题的答案,同时教会他们为什么这是一个答案。作为说明,我通过低质量帖子的审查系统找到了你的答案。这也解释了为什么我留下了你的评论,而不是其他90%的答案几乎相同。
    
    while (!cont.equals("n")) {
        // ...
    }
    
    char cont = 'y';
    while (cont != 'n') {
        // ...
        cont = input.next().charAt(0);
    }
    
    while ( !"n".equalsIgnoreCase(cont) )