Java 从System.in读取的整数值不是键入的值
我是Java的新手,作为练习,我想用一个简单的程序根据用户打印所需数量的“*”字符。但不知何故,此代码的输出始终保持相似:Java 从System.in读取的整数值不是键入的值,java,Java,我是Java的新手,作为练习,我想用一个简单的程序根据用户打印所需数量的“*”字符。但不知何故,此代码的输出始终保持相似: package stars; public class Stars { public static void main(String[] args) { int no_stars=0; try { System.out.print("Enter the number of stars:");
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('*');
}
}
}
包装之星;
公共级明星{
公共静态void main(字符串[]args){
int无星=0;
试一试{
System.out.print(“输入星号:”);
no_stars=(int)System.in.read();
}捕获(例外e){
System.out.println(“错误!无效参数!”);
System.out.println();
}
打印星星(无星星);
}
公共静态无效打印星(int n){
int i;
对于(i=0;i您需要解析从System.in.read()
接收的数字,或者将其作为整数读取,当前您只需强制转换它,因此如果输入5,它将传递0x35次(这是字符“5”的值)
例如,您可以执行以下操作:
Scanner scan = new Scanner( System.in );
printstars( scan.nextInt() );
因为您正在从此处输入读取字符的ASCII码:
no_stars = (int)System.in.read();
应该是
no_stars = Integer.parseInt(Console.readLine());
这将使用用户输入的任何字符的ASCII值。请尝试以下操作:
no_stars = System.in.read() - '0';
或者,将no_stars
变量一起删除
printstars(System.in.read() - '0');
另外,在for
-循环中,为了执行正确的迭代次数,条件应该是i
。并且没有必要在循环之外声明i
,您只需执行for(int i=0;i
代码中有两个错误
首先
System.in.read()
正在读取一个字节,而不是一个整数,因此,它正在解析该整数并获取其第一个字节
秒
for (i = 0; i <= n; i++) {
下面是为您更正的程序:(主要问题是这一行//no_stars=(int)System.in.read();)
publicstaticvoidmain(字符串[]args){
int无星=0;
试一试{
System.out.print(“输入星号:”);
扫描仪sc=新的扫描仪(System.in);
字符串名称=sc.nextLine();
no_stars=Integer.parseInt(名称);
//no_stars=(int)System.in.read();
}
捕获(例外e){
System.out.println(“错误!无效参数!”);
System.out.println();
}
打印星星(无星星);
}
公共静态无效打印星(int n)
{System.out.println(n);
int i;
对于(i=0;i您期望的输出是什么,当前输出是什么样子?在循环之前做一个System.out.println(n);这是一个很好的答案…我对这个很陌生:)谢谢,这很有效。但我仍然不明白为什么我得到50,52或54颗星?即使是System.in.read()只读取第一个字符,我输入了7、10、86、3等整数,在{50,53,54}之间得到了相同的输出。你能解释一下吗?'7'的值为0x37,即55。这足够接近了(考虑到你给出的示例而不是实际值).谢谢,但我还是会被一个字节的输入卡住。我想我会主要使用scanner类。
for (i = 0; i <= n; i++) {
for (i = 0; i < n; i++) {
Scanner scanner = new Scanner(System.in);
no_stars = scanner.nextInt();
public static void main(String[] args) {
int no_stars=0;
try{
System.out.print("Enter the number of stars:");
Scanner sc=new Scanner(System.in);
String name=sc.nextLine();
no_stars = Integer.parseInt(name);
//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)
{System.out.println(n);
int i;
for(i=0;i<=n;i++)
{
System.out.println('*');
}
}