Home > Mobile >  How to use System.in.read() properly
How to use System.in.read() properly

Time:10-12

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.

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related