本文介绍了继续阅读数字,直到使用扫描仪到达换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从控制台读取几个数字。我想这样做的方法是让用户输入一个由空格分隔的数字序列。代码执行以下操作:

I want to read a couple of numbers from the console. The way I wanna do this is by having the user enter a sequence of numbers separated by a space. Code to do the following:

Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()){
    int i = sc.nextInt();

    //... do stuff with i ...
}

问题是,当到达新行时如何停止(同时保持上面易于阅读的代码)?在上面的参数中添加!hasNextLine()会使其立即退出循环。一个解决方案是读取整行并解析数字,但我认为有点破坏了hasNextInt()方法的目的。

The problem is, how do I stop when reaching a new line (while keeping the easy-to-read code above)? Adding a !hasNextLine() to the argument above makes it quit the loop instantly. One solution would be reading the whole line and the parse out the numbers, but I think the kinda ruins the purpose of the hasNextInt() method.

推荐答案

你想设置这样的分隔符:

You want to set the delimiter like this:

Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator")); 
while (sc.hasNextInt()){
    int i = sc.nextInt();

    //... do stuff with i ...
}

更新:

如果用户输入一个数字然后点击输入,则上述代码效果很好。当没有输入数字时按Enter键循环将终止。

The above code works well if the user inputs a number and then hits enter. When pressing enter without having entered a number the program the loop will terminate.

如果您需要(更多地将其理解为可用性的建议)输入分隔的数字空间,看看下面的代码:

If you need (understood it more as a suggestion for usability) to enter the numbers space separated, have a look at the following code:

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);
}

它使用模式为分隔符。我将其设置为匹配空格或行分隔符。因此,用户可以输入空格分隔的数字,然后按Enter键以进行扫描。这可以根据需要用尽可能多的行重复。完成后,用户只需再次输入而不输入数字。输入很多数字时认为这很方便。

It uses a Pattern for the delimiters. I set it to match a white space or a line separator. Thus the user may enter space separated numbers and then hit enter to get them scanned. This may be repeated with as many lines as necessary. When done the user just hits enter again without entering a number. Think this is pretty convenient, when entering many numbers.

这篇关于继续阅读数字,直到使用扫描仪到达换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 22:44