简体   繁体   中英

In Java, why does a Scanner's input.nextInt(3) behave this way?

See code:

Scanner input = new Scanner(System.in);
System.out.println(input.nextInt(3));
//if user inputs 21, then the output is 7

My only understanding is that doing.nextInt(3) turns it into base 3, so only inputs like 10,11,12 or 20,21,22 will be accepted.

But can someone help me understand why nextInt(#) behaves this way, and why inputting 21 outputs 7?

Thanks

The nextInt method you are using accepts an argument for the integer radix that you want to read in. An argument of 3 would read in integers as base 3.

Refer to the Scanner class doc: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt(int)

When you supply an int parameter to nextInt() , that parameter is the radix of the input that's being parsed . In this case, that means the input is parsed in Base-3. And 21 in Base-3 is 7 in Base-10:

00 - 0
01 - 1
02 - 2
10 - 3
11 - 4
12 - 5
20 - 6
21 - 7 // here
22 - 8
// etc.

Basically input.nextInt(x) means that you want to represent the value entered by the user in base x

The output is 7 because 21 is represented as 7 in base 3. You can always use an online calculator to experiment how the same number can be represented in different base.

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