1

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);
}
1
  • 1
    Might want to use "scanner" for simple reading :) Commented Nov 10, 2013 at 21:57

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.