Reputation: 301
I am creating a simple program using the java language which uses a bunch of similar methods to retrieve information from the user. The method i have used to deal with the user entering invalid data seems very incorrect to me, so i am seeking professional guidance on how to better handle invalid data.
I have attempted to search for similar questions but have found none.
This is a sample of one of my methods:
public static int getInput()
{
int temp = 1;
do
{
System.out.println("Answers must be between 1 and 15");
temp = reader.nextInt();
if(temp >=1 && temp <= 15)
{
return temp;
}
else
{
System.out.println("Please enter a valid value");
}
}while(temp > 15 || temp < 1);
//This value will never be reached because the do while loop structure will not end until a valid return value is determined
return 1;
}//End of getInput method
Is there a better way to write this method?
This question is entirely made up so i can learn a better method to implement in my future programs.
Is using a labeled break statement acceptable? such as:
public static int getInput()
{
int temp = 1;
start:
System.out.println("Answers must be between 1 and 15");
temp = reader.nextInt();
if(temp >=1 && temp <= 15)
{
return temp;
}
else
{
System.out.println("Please enter a valid value");
break start;
}
}
Thank you very much in advance.
Upvotes: 2
Views: 11975
Reputation: 11474
You have forgotten to check the case, that non-number values are entered (Scanner#nextInt
throws a java.util.InputMismatchException
). One suggestion which takes care of that issue, is less redundant and more flexible:
public static int getInput(int min, int max) {
for (;;) {
Scanner scanner = new Scanner(System.in);
System.out.println(String.format("Answers must be between %s and %s", min, max));
try {
int value = scanner.nextInt();
if (min <= value && value <= max) {
return value;
} else {
System.out.println("Please enter a valid value");
}
} catch (InputMismatchException e) {
System.out.println("Input was no number");
}
}
}
Upvotes: 2
Reputation: 1767
If you are just worried about the return that is not used and double checking temp you can do something like
public static int getInput()
{
while(true)
{
System.out.println("Answers must be between 1 and 15");
temp = reader.nextInt();
if(temp >=1 && temp <= 15)
{
return temp;
}
else
{
System.out.println("Please enter a valid value");
}
}
}//End of getInput method
Upvotes: 0