繁体   English   中英

从System.in读取的整数值不是键入的值

[英]integer value read from System.in is not the value typed

我是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:");
            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次。

这里似乎有什么问题?

您需要解析从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());
no_stars = (int)System.in.read();

这是使用用户输入的任何字符的ASCII值。 试试这个:

no_stars = System.in.read() - '0';

或者,一起删除no_stars变量,

printstars(System.in.read() - '0');

此外,在for -loop中,条件应为i < n ,以便执行正确的迭代次数。 并且没有必要在循环之外声明i ,你可以做for (int i = 0; i < n; i++)

您的代码中有两个错误。


第一

System.in.read()

读取一个字节,而不是整数,因此,它正在解析整数并获取它的第一个字节。


第二

for (i = 0; i <= n; i++) {

将打印超过要求的一颗星。 所以,它应该改为

for (i = 0; i < n; i++) {

建议:例如,您可以使用扫描仪读取整数

Scanner scanner = new Scanner(System.in);
no_stars = scanner.nextInt();

以下是为您更正的程序:(主要问题是这一行// no_stars =(int)System.in.read();)

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('*');
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM