64,403 views
35 votes
35 votes
Write a method getIntVal that will get the correct value input as integer numbers from the user. The input will be validated based on the first two numbers received as parameters. In other words, your program will keep asking for a new number until the number that the user inputs is within the range of the and . The method should show a message asking for the value within the range as:

User ThinkOfaNumber
by
2.9k points

1 Answer

11 votes
11 votes

Answer:

import java.util.Scanner;

public class Main

{

//Create a Scanner object to be able to get input

public static Scanner input = new Scanner(System.in);

public static void main(String[] args) {

//Ask the user to enter the lowest and highest values

System.out.print("Enter the lowest: ");

int lowest = input.nextInt();

System.out.print("Enter the highest: ");

int highest = input.nextInt();

//Call the method with parameters, lowest and highest

getIntVal(lowest, highest);

}

//getIntVal method

public static void getIntVal(int lowest, int highest){

//Create a while loop

while(true){

//Ask the user to enter the number in the range

System.out.print("Enter a number between " + lowest + " and " + highest + ": ");

int number = input.nextInt();

//Check if the number is in the range. If it is, stop the loop

if(number >= lowest && number <= highest)

break;

//If the number is in the range,

//Check if it is smaller than the lowest. If it is, print a warning message telling the lowest value

if(number < lowest)

System.out.println("You must enter a number that is greater than or equal to " + lowest);

//Check if it is greater than the highest. If it is, print a warning message telling the highest value

else if(number > highest)

System.out.println("You must enter a number that is smaller than or equal to " + highest);

}

}

}

Step-by-step explanation:

*The code is in Java.

You may see the explanation as comments in the code

User Briangonzalez
by
3.0k points