0

i tried to use System.in.read() to get the age of the user. My problem is if i write "24" it gives me the output "you are 50 years old". I googled and saw that it has something to do with the encoding. So 24 is mapped to 50.

Someone recommended to cast integer into char. So it should work. But this time when I put 24, I get the answer "you are 2 years old".

What I want is, that I get the answer "you are 24 years old". How do I do this?

My code below: First Try

public static void main(String[] args) throws IOException {
    System.out.println("Hallo " + args[0]);
    System.out.println("Wie alt bist du?");
    int alter = System.in.read();
    System.out.println("Du bist " + alter + " Jahre alt.");
}

Output: "You are 50 years old."

Second Try:

public static void main(String[] args) throws IOException {
    System.out.println("Hallo " + args[0]);
    System.out.println("Wie alt bist du?");
    char alter = (char) System.in.read();
    System.out.println("Du bist " + alter + " Jahre alt.");
}

Output: "You are 2 years old."

Small Note: "Alter" means age in german.

I hope someone can help me and understands the question. If I can improve something please tell me. Would be appreciated.

  • Is it required that you use `System.in.read()`? because there are other ways to get user input that are in my opinion much better and easier, like using a Scanner. – OH GOD SPIDERS Oct 12 '21 at 09:28
  • No but I wanted to try it out with 'System.in.read()'. Just out of curiosity. – BigChicken97 Oct 12 '21 at 09:31
  • 2
    I agree with @OHGODSPIDERS that there are better ways, I just don't think `Scanner` is one of them ;-) `System.in.read` reads *a single byte of data*, because `System.in` is an `InputStream`. `InputStream` is for reading binary data (or if you don't care what the data is, but just want to move it from one place to the other). For reading text (like what a user is inputting) you should use a `Reader`. – Joachim Sauer Oct 12 '21 at 09:32
  • 1
    The character '2' has ASCII or Unicode value 50. You are looking for line input into a String. I would advise to try the [Console](https://docs.oracle.com/javase/10/docs/api/java/io/Console.html) rather than the more frequent solution of wrapping System.in in a Scanneer. Mind, you probably must run the application in the command line, not the IDE. – Joop Eggen Oct 12 '21 at 09:41
  • Ahhh. Now I see the problem. When I type 24 it only reads the 2 and not the whole number. So this method is not designed to do what I want. – BigChicken97 Oct 12 '21 at 10:02

3 Answers3

2

System.in.read() just reads a single byte - which is not what you want - at least not when really using it.

What happens is, you type in 24 - the 2 of the input is interpreted as byte and you get the ASCII value of that. 2 has the hex value of 0x32 in ASCII, which is 50 in decimal.

See: https://de.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange

You can read multiple single bytes and transform them by calculation to the integer value you want.

A better approach is using Scanner like this:

      import java.util.Scanner;
      [...]
      Scanner scanner = new Scanner( System.in );
      System.out.print( "enter your age: " );
      
      try {
        int age = scanner.nextInt();
        System.out.print("Entered age is : "+ age);
      } catch(InputMismatchException e) {
        System.out.print("Invalid age entered.");
      }
      [...]

You need to handle conditions like entered age should not be a negative integer or no. e.g. 200, if your requirement needs to. For this, you can write if conditions to validate the age value.

Nitish Borade
  • 367
  • 3
  • 18
Mandraenke
  • 3,086
  • 1
  • 13
  • 26
0

Here's one way of making it work, but you should use Console or Scanner

    public static void main(String[] args) {
        try {
            System.out.println("Hallo " + args[0]);
            System.out.println("Wie alt bist du?");
            String accumulator = "";
            do {
                char alter = (char) System.in.read();
                accumulator += alter;
            }
            while (System.in.available() > 0); 
            System.out.println("Du bist " + accumulator.trim() + " Jahre alt.");
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

NB: THE ABOVE IS NOT A RECOMMENDED SOLUTION, MERELY AN ILLUSTRATION

g00se
  • 3,207
  • 2
  • 5
  • 9
0

An example with Console, which allows the entry from passwords and prompts. It also uses formats with placeholders.

Console con = System.console(); // null when there is no console like in the IDE.

con.printf("Hallo %s%n", args[0]);

String answer = con.readLine("Wie alt bist du, %s? ", args[0]);
int alter = answer.matches("\\d+") ? Integer.parseInt(answer) : 13;
con.printf("Du bist %d Jahre alt.%n", alter);

Notice that you need a real command line, otherwise con will be null.

The other disadvantage is that conversion (Integer.parseInt) has to be done by oenself.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138