Ivan Pandžić Ivan Pandžić - 1 month ago 24
Java Question

Java input/output problems

I'm very new with Java, so I wanted to create simple program, which would ask me to input some random value, and then to print it. Problem is when I input number 1, output is 51, input 3-output 51, input 77-output 55. What is wrong with this? Code looks like this:

public static void main(String[] args) throws IOException
{
System.out.print("Input:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int val=br.read();
System.out.print("Output:");
System.out.println(val);
}

Answer

You just read a single char and print the unicode :)

try something like

String s=br.readLine();
System.out.print("Output:");
System.out.println("Input " + s);
int val = Integer.parseInt(s):
System.out.println("As integer: " + val);

If you just want to read a single character:

System.out.print("Input:");
Reader r = new new InputStreamReader(System.in);
int val = r.read();
System.out.print("Output:");
System.out.println((char) val);

If you want to read a single digit:

System.out.print("Input:");
Reader r = new new InputStreamReader(System.in);
int val = r.read() - '0';
System.out.print("Output:");
if (val < 0 || val > 9) {
  System.out.println("error, digit expected");
} else {
  System.out.println(val);
}