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

前端 未结 5 939
执念已碎
执念已碎 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:38

    no_stars = (int)System.in.read();
    

    This is using the ASCII value of whatever character the user enters. Try this instead:

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

    Or, remove the no_stars variable all together,

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

    Also, in your for-loop, the condition should be i < n, in order to perform the correct number of iterations. And there's no need to declare i outside of the loop, you can just do for (int i = 0; i < n; i++).

提交回复
热议问题