-
nextInt() repeat
Hello, im having a rather odd repetition problem when using nextInt. I request a user to input data using :
Code:
private int getInput(int input) {
Scanner b = new Scanner(System.in);
System.out.print("Input " + input + ", please enter input: ");
return b.nextInt();
}
The above works fine however when i try to use b.next int as a parameter in a function it seems to repeat the input process twice, only it doesent output text, it justs prints a blank line on which if i input a number into it carrys on as normal.
Code:
private int getInput(int input) {
Scanner b = new Scanner(System.in);
System.out.print("Input " + input + ", please enter input: ");
printdata(b.nextInt());
return b.nextInt();
The function it is calling does not use b.nextint for anything other than a number, it simply takes the number and prints it. The program is fully functional but i would like it not to request 2 inputs everytime. Im pretty sure it must be from the nextint function but cant figure why?
Any help would be nice :)
Code:
//simple print data function causing the problem
private int printdata(int input) {
saveFile();
System.out.print("saved to file" + input )
}
}
-
Re: nextInt() repeat
You're calling it twice here:
Code:
private int getInput(int input) {
Scanner b = new Scanner(System.in);
System.out.print("Input " + input + ", please enter input: ");
printdata(b.nextInt());
return b.nextInt();
}
So it shouldn't be surprising that you're seeing this behavior. The solution is to call it only once and save the result.
e.g.,
Code:
private int getInput(int input) {
Scanner b = new Scanner(System.in);
System.out.print("Input " + input + ", please enter input: ");
int result = b.nextInt();
printdata(result);
return result;
}
-
Re: nextInt() repeat
massively helpful and a speedy reply, thanks tons!
-
Re: nextInt() repeat
You're welcome. Note that most methods like that wouldn't print out to the console but rather would simply return the result obtained.