Question
How would I try/catch recovery from a format mismatch error? The scanner needs to continue prompting until the user enters a valid number. I know that I would need to try n = kbd.nextInt(); and catch a InputMismatchException and if n<1 or n>100 then I need to print Out of Range Exception. Must be in 1..100. However, I am unsure how to loop all of that. Enter a number between 1 and 100 ti Input not a number. Try again java. lang.Exception: Out of Range Exception. Must be in 1..100 110 Enter a number between 1 and 100 456 Enter a number between 1 and 100 67 You entered 67


import java.io.*;
import java.util.*;

public class Lab5
{
        public static void main( String args[] )
        {

                Scanner kbd = new Scanner(System.in);

                System.out.print("Enter a number between 1 and 100 ");
                System.out.printf("You entered %d\n", kbd.nextInt() );

        } //END main
} //EOF
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.io.*;
import java.util.*;

public class Lab5
{
        public static void main( String args[] )
        {

                Scanner kbd = new Scanner(System.in);
       System.out.print("Enter a number between 1 and 100 ");
       //int n = kbd.nextInt();
       int n;
       while(true)
       {
           try
           {
               n = kbd.nextInt();
               if(n >=1 && n <= 100) {
                   System.out.printf("You entered %d\n", n );
                   break;
               }
               else
                   throw new InputMismatchException();
           }
           catch(InputMismatchException e)
           {
               System.out.print("Format mismatch!!! Reenter a number between 1 and 100 ");
               String s = kbd.next();
               continue;
           }
              
                }

        } //END main
} //EOF

Add a comment
Know the answer?
Add Answer to:
How would I try/catch recovery from a format mismatch error? The scanner needs to continue prompting...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am getting an error from eclipse stating that: Exception in thread "main" java.lang.Error: Unresolved compilation...

    I am getting an error from eclipse stating that: Exception in thread "main" java.lang.Error: Unresolved compilation problem: at EvenOdd.main(EvenOdd.java:10) I am unable to find what I can do to fix this issue. Can you please assist? My code is below: import java.util.InputMismatchException; import java.util.Scanner; public class EvenOdd {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);        System.out.println("Welcome to this Odd program!");        int userInput1 = input.nextInt();    }       public...

  • The Calculator Class Create an application dlass called Colcustor with the following members Methods Retuns firtNumber...

    The Calculator Class Create an application dlass called Colcustor with the following members Methods Retuns firtNumber secondumber static void mainsering Asks for two integer undan uiet", ..",ЛТеп shows the result according to Note Use the attached example program and add required methods. Then une a switch tructure in the try black to call proper method according to the input operator Sample Output 1 : 2074 Sample Output 2 D1VLdeBy LerOWLthEkceptionHahaling-Jav / Handling ArithmeticExceptions and InputMismatchExceptions. import java.util.InputMismatchException; import java.util.Scanner; public...

  • This Exercise contains two classes: ValidateTest and Validate. The Validate class uses try-catch and Regex expressions...

    This Exercise contains two classes: ValidateTest and Validate. The Validate class uses try-catch and Regex expressions in methods to test data passed to it from the ValidateTest program. Please watch the related videos listed in Canvas and finish creating the 3 remaining methods in the class. The regular expression you will need for a Phone number is: "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$" and for an SSN: "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$" This exercise is meant to be done with the video listed in the...

  • I am required to use the try - catch block to validate the input as the...

    I am required to use the try - catch block to validate the input as the test data uses a word "Thirty" and not numbers. The program needs to validate that input, throw an exception and then display the error message. If I don't use the try - catch method I end up with program crashing. My issue is that I can't get the try - catch portion to work. Can you please help? I have attached what I have...

  • I have the following java-program, that creates a random walk starting at (0,0) and continuing until...

    I have the following java-program, that creates a random walk starting at (0,0) and continuing until x or y is greater than abs(n). First: I get an error, when I try closing the Scanner by inserting "reader.close(); " in line 28. It says "Unreachable code". How can I fix that? Second: Is it possible to create a different colour for the StdDraw.point when it reaches a point on one of the edges "n+1" or "n-1" ? 1 import java.util.*; 3...

  • how would i use test.add because i would like to use add import java.io.File; import java.io.FileNotFoundException;...

    how would i use test.add because i would like to use add import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class checkFruit { private List<String> tests; public List<String> getFruit(String fruits) { tests = new ArrayList<String>(Arrays.asList(fruits.split(","))); for (String test : tests) { System.out.println(test); tests.add()//how would i use add here } return tests; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter file name: "); File file = new File(in.nextLine()); try { checkFruit...

  • I am working on this code and keep getting errors like "ERROR: Syntax error: Encountered "<EOF>"...

    I am working on this code and keep getting errors like "ERROR: Syntax error: Encountered "<EOF>" at line 1, column 169." and "ERROR: Table/View 'STUDENT' does not exist. ERROR: Table/View 'STUDENT' does not exist. ERROR: Table/View 'STUDENT' does not exist." I do not know why this isn't working. Here is my code: DTCCDatabase.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * This program creates the CoffeeDB database. */ public class DTCCDatabase {    public static void main(String[] args)...

  • Please edit my following JAVA code so that there is no main function. I would like...

    Please edit my following JAVA code so that there is no main function. I would like one function in this class that completes what the current program is trying to do so that I can call this class in my main class which will be separate. import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Scanner; public class enterwklyincme { private static DecimalFormat df = new DecimalFormat("0.00"); public static float readFloat(Scanner reader) { float num; while (true) { try { num = Float.parseFloat(reader.nextLine()); return...

  • Please provide the full code...the skeleton is down below: Note: Each file must contain an int...

    Please provide the full code...the skeleton is down below: Note: Each file must contain an int at the beginning, stating the number of records in the file. Afterwards, the number of records in the file will follow. Each record that follows will consist of a last name (String), and a gpa (double). However, to test the error handling of your program, the number of records will not always match the int value. All possible combinations should be tested. 1.) Prompt...

  • Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac...

    Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac -g P4Program.java P4Program.java:94: error: package list does not exist Iterator i = new list.iterator(); ^ 1 error ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete. Note: Below there are two different classes that work together. Each class has it's own fuctions/methods. import java.util.*; import java.io.*; public class P4Program{ public void linkedStackFromFile(){ String content = new String(); int count = 1; File...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT