[英]How can I take either two or one integer as input on the same line in Java?
For example, how can I take the either values 1 0
or just the value 2
to then be used at a latter part of the program.例如,如何取值
1 0
或仅取值2
然后在程序的后期使用。 Say that 1
adds the number 0
to a list and 2
prints out a phrase.假设
1
将数字0
添加到列表中,而2
打印出一个短语。 Right now I only know how to take two numbers on the same line using现在我只知道如何使用在同一行上取两个数字
Scanner sc = new Scanner(System.in); // receives input for x y
int x = Integer.parseInt(sc.next());
int y = Integer.parseInt(sc.next());
Just put spaces between terms:只需在术语之间放置空格:
Scanner scanner = new Scanner(System.in);
int[] values = new int[2];
String[] arguments = scanner.nextLine().split(" ");
for(int i = 0; i < arguments.length && i < values.length; i++){
values[i] = Integer.parseInt(arguments[i]);
}
scanner.close();
On line 2 you specify maximum inputs在第 2 行,您指定最大输入
On line 3 in the "" you can specify what goes between terms在“”的第 3 行,您可以指定术语之间的内容
On line 2 & 5 you can specify term type在第 2 行和第 5 行,您可以指定术语类型
Just adding to @Devon Rutledge
's answer, that Scanner class separates tokens (in this case, numbers) on the condition that there are 1 or more spaces between them.只是添加到
@Devon Rutledge
的答案中,该 Scanner 类在标记(在本例中为数字)之间有 1 个或多个空格的情况下分隔标记。
Hence, as Devon mentioned above, you should add spaces between the inputs.因此,正如上面提到的 Devon,您应该在输入之间添加空格。
However, the answer posted above works the exact same way as a normal sc.next()
would, albeit with a problem that if you enter two spaces between inputs, it will five an error.但是,上面发布的答案的工作方式与正常的
sc.next()
完全相同,尽管存在一个问题,即如果您在输入之间输入两个空格,则会出现五个错误。 So there's no problem with your code, per se, but just the inputs.所以你的代码本身没有问题,但只是输入。
If you do want to accept single-digit numbers without spaces, then you can try this:如果你确实想接受没有空格的个位数,那么你可以试试这个:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("");
int x = sc.nextInt();
int y = sc.nextInt();
Also, it is better to use sc.nextInt()
, as sc.next()
would accept even the letters, which cannot not be converted to int
.此外,最好使用
sc.nextInt()
为sc.next()
甚至会接受的字母,这不能不能转换为int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.