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

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

    There are two mistakes in your code.


    First

    System.in.read()
    

    Is reading a byte, not a integer, so, it is parsing the integer and getting the first byte of it.


    Second

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

    will print always one star more than requested. So, it should be changed to

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

    Suggestion: You could use Scanner to read your integer, for example

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

提交回复
热议问题