In order to make my program more streamlined (Without try and catch everywhere), I tried to create a seperate method just for getting data. I have one for Doubles, and Strings, as well.
For some reason, when I try to use this method, it is completely ignored, and passed by like a comment. Is there something I’m doing wrong?
public int inputint(){
Scanner sc = new Scanner (System.in);
int variable = 0;
boolean valid = true;
do{
try{
if (variable >= 0 && valid){
}
else if(valid){
System.out.print("Please enter positive values only: ");
}
valid = true;
}
catch (InputMismatchException e){
System.out.print("Please enter numerical values only: ");
sc = new Scanner(System.in);
valid = false;
}
}while (!valid || variable < 0);
return variable;
}
Well first of all, you’re code is insanely hard to understand. (or could just be me I guess)
But if you look at your code
You are creating the Scanner object, but nowhere in the method are you actually using it.
The next few lines,
both of those conditions are met. So with nothing in the brackets, no code is executed. So from there, it just returns the value of the variable, which is 0.
So you need to actually use your Scanner class to grab an integer. Which I believe, though I’m not sure, the method for that is
Edit: From the JavaDocs http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
You can simply use
to read an integer from the Scanner.