简体   繁体   中英

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. Say that 1 adds the number 0 to a list and 2 prints out a phrase. 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

On line 3 in the "" you can specify what goes between terms

On line 2 & 5 you can specify term type

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.

Hence, as Devon mentioned above, you should add spaces between the inputs.

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. 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 .

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