Java application that uses a loop control structure. Use the Scanner class to ac
ID: 3775252 • Letter: J
Question
Java application that uses a loop control structure. Use the Scanner class to accept a number between 1 and 10 from the user. While the number entered is not between 1 and 10 (inclusive), an error message will be displayed “The number entered was not between 1 and 10!” and the program will loop back to prompt the user for another number. If the number entered is between 1 and 10 (inclusive), the application will display a message “Good job! The number you entered is ” and the program will end.
package assignment_4_2;
import java.util.Scanner;
public class Assignment_4_2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int userNumber;
Scanner reader = new Scanner(System.in); // The scanner to read the user input
System.out.print("Enter a number between 1 and 10: ");
userNumber = reader.nextInt(); // We give the user the option to give a number, and we store it in input
while(userNumber > 10 || userNumber < 1)
{
//System.out.println("Good job! The number you entered is " +userNumber+".");
System.out.println("The number entered was not between 1 and 10! Please enter a number between 1 and 10:");
userNumber = reader.nextInt();
}
//System.out.println("The number entered was not between 1 and 10! Please enter a number between 1 and 10:");
System.out.println("Good job! The number you entered is " +userNumber+".");
}
Explanation / Answer
Hi,
I dont see any issue with this code. It is working as expected.
Assignment_4_2.java
import java.util.Scanner;
public class Assignment_4_2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int userNumber;
Scanner reader = new Scanner(System.in); // The scanner to read the user input
System.out.print("Enter a number between 1 and 10: ");
userNumber = reader.nextInt(); // We give the user the option to give a number, and we store it in input
while(userNumber > 10 || userNumber < 1)
{
System.out.println("The number entered was not between 1 and 10! Please enter a number between 1 and 10:");
userNumber = reader.nextInt();
}
System.out.println("Good job! The number you entered is " +userNumber+".");
}
}
Output:
Enter a number between 1 and 10: 11
The number entered was not between 1 and 10! Please enter a number between 1 and 10:
11
The number entered was not between 1 and 10! Please enter a number between 1 and 10:
13
The number entered was not between 1 and 10! Please enter a number between 1 and 10:
-5
The number entered was not between 1 and 10! Please enter a number between 1 and 10:
5
Good job! The number you entered is 5.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.