简体   繁体   中英

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. 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!");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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