[英]In Java, why does a Scanner's input.nextInt(3) behave this way?
见代码:
Scanner input = new Scanner(System.in);
System.out.println(input.nextInt(3));
//if user inputs 21, then the output is 7
我唯一的理解是,doing.nextInt(3) 将其转换为基数 3,因此只接受 10,11,12 或 20,21,22 之类的输入。
但是有人能帮我理解为什么 nextInt(#) 会这样,为什么输入 21 输出 7?
谢谢
您正在使用的 nextInt 方法接受您想要读入的整数基数的参数。 参数 3 将作为基数 3 读入整数。
参考扫描器类文档: https : //docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt(int)
当您向nextInt()
提供int
参数时,该参数是正在解析的输入的基数。 在这种情况下,这意味着输入是在 Base-3 中解析的。 Base-3 中的 21 是 Base-10 中的 7:
00 - 0
01 - 1
02 - 2
10 - 3
11 - 4
12 - 5
20 - 6
21 - 7 // here
22 - 8
// etc.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.