-2

I am really new to Java, and I was following a book tutorial on how to read user input. Their code was...

class Example {
    public static void main(String args[]) throws java.io.IOException {
        // System.out.println()
        char ch;

        System.out.print("Press a key followed by ENTER: ");
        ch = (char) System.in.read();
        System.out.println("Your key is: " + ch);
    }
}

I tried to experiment and read user input as an integer like this...

class Example {
    public static void main(String args[]) throws java.io.IOException {
        int foo;

        System.out.print("Enter a number: ");
        foo = (int) System.in.read();

        System.out.print("Your number was: " + foo);
    }
}

However, upon typing for example number 12, I get the output as 49. Why is that? How come the book tutorial worked then?

EDIT: When I type in 'w' in my program, it still prints out 119. Surely I thought the throws thing was dealing with that? Or is it not?

And what is a Scanner (just saw it in the comments)?

Bob
  • 3
  • 3
  • 1
    Use a Scanner. `49` is the ASCII for `1`. The `read()` function reads the next **byte** from the InputStream. – Abhyudaya Sharma Dec 27 '18 at 13:43
  • Both the linked duplicate question and accepted answer are old / pretty bad, please skip directly to [this answer](https://stackoverflow.com/a/34120618/2707792). – Andrey Tyukin Dec 27 '18 at 13:46
  • Scanner is a built in method of java used to read data from the console. It is included in utility package. – Codemaker Dec 27 '18 at 13:50
  • "_And what is a Scanner_" See https://stackoverflow.com/questions/11871520/how-can-i-read-input-from-the-console-using-the-scanner-class-in-java – Ivar Dec 27 '18 at 13:50
  • @HovercraftFullOfEels Maybe add [How can I get the user input in Java?](https://stackoverflow.com/q/5287538/2707792) to the list of duplicates? – Andrey Tyukin Dec 27 '18 at 13:52

2 Answers2

0

System.in.read() Reads the next byte of data from the input stream. So you are just reading 1 from input and you are printing ASCII code of 1 which is 49. If you want to show the character you should read it as char or convert it:

System.out.print("Your number was: " + (char) foo)
Spara
  • 4,114
  • 2
  • 20
  • 47
0

Answering Your Question

However, upon typing for example number 12, I get the output as 49.Why is that?

The reason you got 49, is because you only read the first char of the input (the program only read the '1' digit). The ASCII value of 1, surprisingly equals to 49.

Better Approach

I would suggest to use the Scanner object to read inputs from System.in, like this.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence:\t");
String sentence = scanner.nextLine();

This approach will populate the 'sentence' String, with the entire line entered in the console.

If you need a number and not a String, parse that string to an int using Integer.valueOf(yourString);

Daniel B.
  • 1,988
  • 1
  • 6
  • 21