Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java Program Write a method named getOneToTen that has one parameter; prompt (ty

ID: 3576652 • Letter: J

Question

Java Program

Write a method named getOneToTen that has one parameter; prompt (type String class). prompt should be printed whenever the user needs to enter a token. The method should return an int value between 1 and 10 read in from the keyboard. A while loop that includes a look ahead method (a scanner method that tests values before they are read) should be used to handle possible user errors: the user might enter a value less than 1, the user might enter a value larger than 10, or the user might enter a token that is not an int. You can assume that java.util.* has been imported and that CONSOLE is a Scanner class constant for reading from the keyboard.

Explanation / Answer

ReadValue.java


import java.util.InputMismatchException;
import java.util.Scanner;

public class ReadValue {

  
   public static void main(String[] args) {
       int n = getOneToTen("Enter an integer between 1 and 10: ");
       System.out.println("You entered: "+n);
   }
   public static int getOneToTen (String s){
       Scanner scan = new Scanner(System.in);
       int n = 0;
       while(n<1 ||n > 10){
           try{
           System.out.println(s);
           n= scan.nextInt();
           }
           catch(InputMismatchException e){
               System.out.println("Input must be between 1 and 10 and numeric");
               scan.nextLine();
           }
       }
       return n;
   }
}

Output:

Enter an integer between 1 and 10:
11
Enter an integer between 1 and 10:
0
Enter an integer between 1 and 10:
aa
Input must be between 1 and 10 and numeric
Enter an integer between 1 and 10:
4
You entered: 4

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote