Java 如何从用户输入中断或继续循环

Java 如何从用户输入中断或继续循环,java,Java,我试着写一个代码,当输入y时循环,当输入n时停止,这就是我到目前为止所做的 Scanner input = new Scanner(System.in); do{ System.out.println("She sells seashells by the seashore."); System.out.println("Do you want to hear it again?"); }while (input.hasNext());{

我试着写一个代码,当输入y时循环,当输入n时停止,这就是我到目前为止所做的

Scanner input = new Scanner(System.in);
do{ 
    System.out.println("She sells seashells by the seashore.");
    System.out.println("Do you want to hear it again?");
}while (input.hasNext());{
input.hasNext("y");
   }

我不知道如何继续。

如果您坚持使用do…,那么您可以尝试:

Scanner input = new Scanner(System.in);
do{ 
    System.out.println("She sells seashells by the seashore.");
    System.out.println("Do you want to hear it again?");
}while (input.hasNext() && !input.next().equals("n"));

要获得更可读的代码,可以使用布尔变量,并根据输入等于“y”的条件将其赋值为true

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        boolean stopFlag= false;
        do{
            System.out.println("She sells seashells by the seashore.");
            System.out.println("Do you want to hear it again?");
            String userInput =input.next();
            if(!userInput.equals("y"))
                stopFlag=true;
        }while (!stopFlag);
    }
您可以这样做:

Scanner input = new Scanner(System.in);
while(input.hasNext()) {
    String temp = input.next();
    if(temp.equals("y")) {
        // if you need to do something do it here
        continue; // will go to the next iteration
    } else if(temp.equals("n")) {
        break; // will exit the loop
    }
}

如果用户输入
y
,则不会重复循环。事实上,只有当用户没有输入
y
时,它才会重复。您可以根据需要更改第二个条件,但逻辑仍然成立。您可以将其转换为
!input.next().equals(“n”)
并在所有其他情况下继续。您当前的回答与OP要求的完全相反。我已将其更改为break for input=“n”。但是这个问题仍然很模糊,因为它说继续在“y”上,中断在“n”上。如果输入了其他内容呢?我想你是对的。