简体   繁体   English

Java while 循环在“break”语句后不会中断

[英]Java while loop not breaking after "break" statement

import java.util.Scanner;

public class LoopsEndingRemembering {
    public static void main(String[] args) {
        // program in this project exercises 36.1-36.5
        // actually this is just one program that is split in many parts

        Scanner reader = new Scanner(System.in);

       System.out.println("Type numbers: ");
       int input = Integer.parseInt(reader.nextLine());

       while(true){

           if(input == -1){
               break;
           }

         }



       System.out.println("Thank you and see you later!");


    }
}

The user should be able to put in multiple numbers until -1 is reached.用户应该能够输入多个数字,直到达到 -1。 Once its reached it should break the loop and print the last line.一旦到达它应该打破循环并打印最后一行。

You need to put你需要把

 System.out.println("Type numbers: ");
 int input = Integer.parseInt(reader.nextLine());

into your loop, else it will never get new user input进入你的循环,否则它永远不会得到新的用户输入

You need call scanner inside loop您需要在循环内调用扫描仪

import java.util.Scanner;
public class LoopsEndingRemembering {

public static void main(String[] args) {

 while(true){
           Scanner reader = new Scanner(System.in);
           System.out.println("Type numbers: ");
           int input = Integer.parseInt(reader.nextLine());
               if(input == -1){
                   break;
               }
             }
           System.out.println("Thank you and see you later!");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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