简体   繁体   中英

Java - Is there any way to break while loop while scanning integers in ArrayList without giving invalid input?

The while loop breaks only if I give some non-integer input. What I want is to break it with blank input (just hit "Enter" without any input)

import java.util.ArrayList;
import java.util.Scanner;

public class SingleElement {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    ArrayList<Integer> list = new ArrayList<Integer>();
    int in = (Integer) null;
    while(scan.hasNextInt()){   
        list.add(scan.nextInt());
    }
  }
}

Thanks!

Not really.

The program has a hard coded expectation to only find a list of incoming numbers.

So you would have to define a special number to mean: stop looping.

To make things easier to control, you could read raw strings from the scanner. And then any non number means: stop looping.

You should parse the input as a String and then convert that into an int via code within a try/catch . If you get an exception in converting the String into int , you know you got a non-integer, and you can break the while loop from there.

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