Question

For practice using exceptions, this exercise will use a try/catch block to validate integer input from...

For practice using exceptions, this exercise will use a try/catch block to validate integer input from a user. Write a brief program to test the user input. Use a try/catch block, request user entry of an integer, use Scanner to read the input, throw an InputMismatchException if the input is not valid, and display "This is an invalid entry, please enter an integer" when an exception is thrown. InputMismatchException is one of the existing Java exceptions thrown by the Scanner if the input does not match the type requested., For more information see this site: https://docs.oracle.com/javase/8/docs/api/java/util/InputMismatchException.html. Submit your working file and execution screenshot. The execution screenshot should show that the exception is thrown and the message is displayed for an invalid input.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Java Program :

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

public class Main
{
   public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
       int value;
       try {
       System.out.println("Enter an integer value");
       value = s.nextInt();
       System.out.println("Value = " + value);
      
       }
       catch(InputMismatchException e)
       {
       System.out.println("This is an invalid entry, please enter an integer");
       }
      
   }
}


Output:

When there's an exception :

Enter an integer value This is an invalid entry, please enter an integer

When there's no exception

Enter an integer value Value = 6

Add a comment
Know the answer?
Add Answer to:
For practice using exceptions, this exercise will use a try/catch block to validate integer input from...
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 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...

  • In this assignment you will practice using Data Structures and Object Oriented concepts in Java. Your implementation should target the most efficient algorithms and data structures. You will be graded...

    In this assignment you will practice using Data Structures and Object Oriented concepts in Java. Your implementation should target the most efficient algorithms and data structures. You will be graded based on the efficiency of your implementation. You will not be awarded any points if you use simple nested loops to implement the below tasks. You should use one or more of the below data structures: - ArrayList : - JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html - Tutorial: http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html Question You are provided with...

  • 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...

  • import java.util.Scanner; import java.io.File; public class Exception2 {        public static void main(String[] args) {              ...

    import java.util.Scanner; import java.io.File; public class Exception2 {        public static void main(String[] args) {               int total = 0;               int num = 0;               File myFile = null;               Scanner inputFile = null;               myFile = new File("inFile.txt");               inputFile = new Scanner(myFile);               while (inputFile.hasNext()) {                      num = inputFile.nextInt();                      total += num;               }               System.out.println("The total value is " + total);        } } /* In the first program, the Scanner may throw an...

  • How would I try/catch recovery from a format mismatch error? The scanner needs to continue prompting...

    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. import java.io.*; import java.util.*; public class Lab5 { public static void main( String args[]...

  • 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...

  • Lesson is about Input validation, throwing exceptions, overriding toString Here is what I am supposed to...

    Lesson is about Input validation, throwing exceptions, overriding toString Here is what I am supposed to do in the JAVA Language: Model your code from the Time Class Case Study in Chapter 8 of Java How to Program, Late Objects (11th Edition) by Dietel (except the displayTime method and the toUniversalString method). Use a default constructor. The set method will validate that the hourly employee’s rate of pay is not less than $15.00/hour and not greater than $30.00 and validate...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • IT Java code In Lab 8, we are going to re-write Lab 3 and add code...

    IT Java code In Lab 8, we are going to re-write Lab 3 and add code to validate user input. The Body Mass Index (BMI) is a calculation used to categorize whether a person’s weight is at a healthy level for a given height. The formula is as follows:                 bmi = kilograms / (meters2)                 where kilograms = person’s weight in kilograms, meters = person’s height in meters BMI is then categorized as follows: Classification BMI Range Underweight Less...

  • 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...

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