从System.in读取的整数值不是键入的值 [英] integer value read from System.in is not the value typed
本文介绍了从System.in读取的整数值不是键入的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java的新手,并且作为一个练习想要一个简单的打印程序需要没有。根据用户的'*'字符。但不知何故,此代码的输出始终保持相似:
I am a newbie to Java, and as an exercise wanted to WAP a simple program to print required no. of '*' characters according to the user. But somehow, the output of this code always remains similar:
package stars;
public class Stars {
public static void main(String[] args) {
int no_stars=0;
try {
System.out.print("Enter the number of stars:");
no_stars = (int)System.in.read();
} catch ( Exception e) {
System.out.println("Error! Invalid argument!");
System.out.println();
}
printstars(no_stars);
}
public static void printstars(int n){
int i;
for(i=0;i<=n;i++)
{
System.out.println('*');
}
}
}
如果我用i替换'*',我可以看到它循环到50/52/54,即使我运行循环no_stars次。
If I replace '*' with i, I can see that it loops upto 50/52/54, even though i run the loop no_stars times.
这里的问题似乎是什么?
What seems to be the problem here?
推荐答案
因为您正在读取输入字符的ASCII码:
Because you are reading ASCII code of the character from input here:
no_stars = (int)System.in.read();
应该是
no_stars = Integer.parseInt(Console.readLine());
这篇关于从System.in读取的整数值不是键入的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文