Sna*_*ail 5 java numbers input java.util.scanner
我想从控制台读取几个数字.我想这样做的方法是让用户输入一个由空格分隔的数字序列.代码执行以下操作:
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()){
int i = sc.nextInt();
//... do stuff with i ...
}
Run Code Online (Sandbox Code Playgroud)
问题是,当到达新行时如何停止(同时保持上面易于阅读的代码)?在上面的参数中添加!hasNextLine()会使其立即退出循环.一种解决方案是读取整行并解析数字,但我认为有点破坏了hasNextInt()方法的目的.
您想要像这样设置分隔符:
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));
while (sc.hasNextInt()){
int i = sc.nextInt();
//... do stuff with i ...
}
Run Code Online (Sandbox Code Playgroud)
更新:
如果用户输入一个数字然后点击输入,上面的代码很有效.当没有输入数字时按Enter键循环将终止.
如果您需要(更多地将其理解为可用性的建议)输入分隔的数字空间,请查看以下代码:
Scanner sc = new Scanner(System.in);
Pattern delimiters = Pattern.compile(System.getProperty("line.separator")+"|\\s");
sc.useDelimiter(delimiters);
while (sc.hasNextInt()){
int i = sc.nextInt();
//... do stuff with i ...
System.out.println("Scanned: "+i);
}
Run Code Online (Sandbox Code Playgroud)
它使用a Pattern作为分隔符.我将其设置为匹配空格或行分隔符.因此,用户可以输入空格分隔的数字,然后按Enter键以进行扫描.这可以根据需要用尽可能多的行重复.完成后,用户只需再次输入,而无需输入数字.输入很多数字时认为这很方便.