# Get valid x() within ranges

I can’t figure out how to write the method that can do input validation within ranges. The teacher gave the starter code and I just have to create the method! But my brain is not working.

here is the code with instructions:

package week9;

import java.util.Scanner;

public class Lab9i {

``````public static void main(String[] args) {
//Initialize local variables
Scanner sIn = new Scanner(System.in);	//Input Scanner for String
int intNum = 0;
double doubleNum = 0;
String choice = "";
String playAgain = "Y";

//Keep program running until user wants to quit
do {
//Get an integer from the user
int[] intRange1 = {};
intNum = getValidInt(sIn, "Please enter a whole number: ", "Invalid response. Only whole numbers are acceptable.",intRange1);
System.out.println("The whole number your entered was: "+ intNum);
System.out.println("Now we will test your whole number in a math equation...");
System.out.printf("Adding 10 to your whole number would be: 10 + %d = %d.\n\n",intNum, (intNum + 10));

//Get an integer within a range from the user
int[] intRange2 = {10, 50};
intNum = getValidInt(sIn, "Please enter a whole number between 10 and 50: ", "Invalid response. Only whole numbers between 10 and 50 are acceptable.",intRange2);
System.out.println("The whole number your entered was: "+ intNum);
System.out.println("Now we will test your whole number in a math equation...");
System.out.printf("Adding 10 to your whole number would be: 10 + %d = %d.\n\n",intNum,(intNum + 10));
``````

// and now the method that I am creating with the instructions

}//end of method main()

``````/**getValidInt method validates user input is an Integer within range and returns it back to the calling method.
* Uses sIn to get user input from the console.
* Asks user question.
* If range is empty, range is ignored and only validates input is an integer.
* If range is not empty, validates user input is an integer within range.
* If user input is not valid, prints warning and repeats question.
* Returns validated input.
*/
public static int getValidInt(Scanner sIn, String question, String warning, int[] range){
int num1 = 0;
int num2 = 0;

boolean valid = false;
while(!valid) {
System.out.println(question);
String input = sIn.nextLine();

try {
num1 = Integer.parseInt(input);
valid = true;
} catch (Exception e) {
System.out.println(warning);
} // end of try catch

} // end of while

return num1;

}//end of method getValidInt(Scanner, String, String, int[])``````

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.