integer value read from System.in is not the value typed

前端 未结 5 918
执念已碎
执念已碎 2021-01-18 03:22

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 cod

5条回答
  •  無奈伤痛
    2021-01-18 03:52

    Here is the corrected program for you: (the main problem was this line //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('*');
    }
    }
    

提交回复
热议问题