Java 重复输出
在下面的代码示例中,为什么低于9的编号在我的控制台中打印两次Java 重复输出,java,io,console,Java,Io,Console,在下面的代码示例中,为什么低于9的编号在我的控制台中打印两次 public static void main(String[] args) throws java.io.IOException { System.out.println("Input from keyboard should be '49'"); char e; for (int a = 0; ; a++) { e = (char) System.in.read(); if
public static void main(String[] args) throws java.io.IOException {
System.out.println("Input from keyboard should be '49'");
char e;
for (int a = 0; ; a++) {
e = (char) System.in.read();
if (e == 49)
break;
else
System.out.println("Use number lower than 9");
}
}
这是当您键入除数字1以外的任何内容时的输出:
run:
Input from keyboard should be '49'
2
Number lower than 9
Number lower than 9
编辑
基本上,我正在尝试从控制台获取输入并将其存储在
chare
中。键入1
后得到的是值49
。这就是为什么我在上面的代码中使用e==49
。我不知道如何检索字符1
。接下来,我使用一个无限循环强制输入请求特定字符,直到它是正确的字符 当您在命令行中输入2
时,您实际上输入了2\n
(其中\n
为换行符),通过按enter或Return确认输入
System.in.read()
因此在第一个循环周期中返回一个2
,在第二个循环周期中返回换行符,每次在标准输出上打印消息
可以通过跳过换行符来解决此问题:
for (int a = 0; ; a++) {
e = (char) System.in.read();
if (e == '\n')
continue;
if (e == 49)
break;
else
System.out.println("Use number lower than 9");
}
不过还有一些问题:你想实现什么?如果在基于字符的级别上比较输入,49
不等于数字49,而是等于带有代码49的字符,即字符'1'
其次,如果你正在构建一个无止境的循环,你也应该这样写。for循环给人的印象是,循环将根据您的inta
,而不是这样。要编写无休止的循环,您只需编写:
while (true) {
// do something
if (checksomething())
break;
}
您可以只扫描字符串,但如果您需要字符,上面的代码可以工作您的程序输出显示小于9的数字,因为它
System.in.read()
返回输入的第一个字符的ASCII值,即“2”,而不是49或50
如果您想要整数作为输入,可以使用以下代码inti=newscanner(System.in).nextInt()代码>
参考此
read()不读取数字,它读取一个字节并返回其值
作为一个整数。如果你输入一个数字,你会得到48+这个数字,因为
数字0到9在ASCII中的值为48到57
编码
Enter被计为一个字符,因此是另一个字符条目
如果您只想存储字符1
,则无需强制转换它
if (e == 49) {
//Presume that is character `1` and do what operation you want as it is.
System.out.println("You enter number 1");
}
相反,您应该检查输入是否正确,然后将其转换为字符。您可以通过检查输入if是否介于48
和57
之间来检查输入if是否为我在引号中所写的数字记住,如果您键入,例如57被计为两个输入(5和7)
char ch; int e;
if (e >= 49 && e <= 57) {
ch = (char)e;
System.out.println("You enter number " + ch);
}
charch;INTE;
如果(e>=49&&e)看到您从未在代码中打印“数字小于9”。。。
if (e == 49) {
//Presume that is character `1` and do what operation you want as it is.
System.out.println("You enter number 1");
}
char ch; int e;
if (e >= 49 && e <= 57) {
ch = (char)e;
System.out.println("You enter number " + ch);
}