when I get an input from the user I want to make sure that it is both:
I wrote the following code to achieve this but it seems more convoluted than it has to be. Is there a way to consolidate the question is the input a number and is that number less than ten, or any similar two part validation?
// function prompts user for a double greater than number passed in
// continues to prompt user until they input a number greater than
// the minimum number
public static double getInput(double minimumInput) {
Scanner scan = new Scanner(System.in);
double userInput;
System.out.print("Enter a number greater than " + minimumInput + ": ");
while (!scan.hasNextDouble()){
String garbage = scan.next();
System.out.println("\nInvalid input.\n");
System.out.print("Enter a number greater than " + minimumInput + ": ");
} // end while
userInput = scan.nextDouble();
while (userInput <= minimumInput) {
System.out.println("\nInvalid input.\n");
userInput = getInput(minimumInput);
}
return userInput;
} // end getInput
Simple answer: there is not.
You see, user input can be anything. If you would not be using that "nextDouble()" method your code would even have to do that conversion of strings into numbers. But there is no way in java to say: this thing is a double, and it must be smaller than some other value.
You explicitly have to "put down" that constraint into code. And the code you have right now is fine in that perspective. I even think it is better than the proposal within the other answer that tries to stuff all those tests into a single if condition.
You see, good code can be read and understood easily. Of course, "less code" is often quicker to read, but sometimes a "bit more" of code can be understood much quicker than the shorter version!