Java Scanner—当项目总数未知时,分隔的输入空间加倍

Java Scanner—当项目总数未知时,分隔的输入空间加倍,java,input,java.util.scanner,Java,Input,Java.util.scanner,我有一个在Eclipse中运行的简单Java程序。在命令行中,我传入了一个大约100个空格分隔的双精度列表,但是,请假设我不知道可以传入多少项 目前我正在阅读整行内容,然后标记化并转换为double,如下所示: Scanner sc = new Scanner(System.in); ArrayList<Double> stock = new ArrayList<Double>(); String s = sc.nextLine();

我有一个在Eclipse中运行的简单Java程序。在命令行中,我传入了一个大约100个空格分隔的双精度列表,但是,请假设我不知道可以传入多少项

目前我正在阅读整行内容,然后标记化并转换为double,如下所示:

    Scanner sc = new Scanner(System.in);

    ArrayList<Double> stock = new ArrayList<Double>();

    String s = sc.nextLine();

    String[] split = s.split("\\s+");

    for (int i=0; i<split.length; i++)
    {
        stock.add(Double.parseDouble(split[i]));
    }
Scanner sc=新扫描仪(System.in);
ArrayList stock=新的ArrayList();
字符串s=sc.nextLine();
字符串[]split=s.split(\\s+);

对于(inti=0;i来说,这是因为while循环。 程序将永远等待System.in的更多输入,因为sc.hasNextDouble()每次都将求值为true,因为System.in的输入是无限的,而不是来自文件的输入

对我来说,你的第一个解决办法似乎是,如果你想把所有的双打都排在一行的话。 但是您可以稍微清理一下,使用for-each而不是常规的for循环

例如:

Scanner scanner = new Scanner(System.in);

ArrayList<Double> doubles = new ArrayList<Double>();

String inputLine = scanner.nextLine();
String[] splittedInputLine = inputLine.split("\\s+");

for(String doubleString : splittedInputLine) {
    doubles.add(Double.parseDouble(doubleString));
}
Scanner Scanner=新的扫描仪(System.in);
ArrayList doubles=新的ArrayList();
字符串inputLine=scanner.nextLine();
字符串[]splittedInputLine=inputLine.split(\\s+);
for(字符串doubleString:splittedInputLine){
doubles.add(Double.parseDouble(doubleString));
}

谢谢你,莫顿。我感谢你的回复,因为这有助于我澄清问题。:)
Scanner scanner = new Scanner(System.in);

ArrayList<Double> doubles = new ArrayList<Double>();

String inputLine = scanner.nextLine();
String[] splittedInputLine = inputLine.split("\\s+");

for(String doubleString : splittedInputLine) {
    doubles.add(Double.parseDouble(doubleString));
}