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.
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- the2of the input is interpreted as byte and you get the ASCII value of that.2has 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
Scannerlike this: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
ifconditions to validate theagevalue.