Reputation: 75
I'm trying to make an inputhandler in Java. This is (a snippet of) the source code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Inputhandler{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public int InputInt;
public int GetInt(){
try{
InputInt = br.read();
} catch(Exception e){
System.out.println("Input should be a number. Please try again\n");
GetInt();
}
return InputInt;
}
}
I'm trying to get the user input from line 10, and then set that input as the value of InputInt. However, when I execute the program and call the method like this:
Inputhandler in = new Inputhandler();
int a = in.GetInt("A question"); //I would input a number like 200
System.out.println(a);
It prints out, at least that's what it looks like it to me, a random number. Numbers like 51, 48, 55. What am I doing wrong here? Why isn't the number that I input assigned to InputInt?
I sorted it would have something to do with the pass-by-reference and pass-by-value, and I understand those principles. I (think I) fully understand this and can still not work it out.
Please help me out! Thanks in advance.
Upvotes: 0
Views: 81
Reputation: 1747
Your int
is actually the byte value of a character you enter. Try
InputInt = Integer.valueOf(br.readLine());
instead.
Upvotes: 1