Reputation: 373
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);
}
Upvotes: 1
Views: 345
Reputation: 21
you can also use BufferedReader as
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
input number = Integer.parseInt(input);
System.out.println(input);
}
Upvotes: 1
Reputation: 18793
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);
}
Upvotes: 3