Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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 code always remains similar:

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

    }


}

If I replace '*' with i, I can see that it loops upto 50/52/54, even though i run the loop no_stars times.

What seems to be the problem here?

like image 798
Akash Avatar asked Jun 13 '13 17:06

Akash


People also ask

What is system in read ()?

int System. in. read() reads the next byte of data from the input stream.

How does system in work in Java?

System.in: An InputStream which is typically connected to keyboard input of console programs. It is nothing but an in stream of OS linked to System class. Using System class, we can divert the in stream going from Keyboard to CPU into our program. This is how keyboard reading is achieved in Java.


1 Answers

You need to parse the number received from System.in.read() or alternatively read it as an integer, currently you just cast it, so if you enter 5, it passes 0x35 times (which is the value of the character '5')

You can do, for example:

Scanner scan = new Scanner( System.in );
printstars( scan.nextInt() );
like image 130
MByD Avatar answered Oct 15 '22 20:10

MByD