Question

In: Computer Science

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.

Solutions

Expert Solution

Please upvote if you like the answer, as it helps the community a lot.

Also if you have any doubts, feel free to ask in comments, we will reach you ASAP.

Code(Solution.Java):

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

/* Name of the class has to be same as file name. */
class Solution
{
   public static void main (String[] args) throws java.lang.Exception
   {
       // your code goes here
       Scanner sc = new Scanner(System.in);

//Try Catch Block
       try{
           int x = sc.nextInt();
           System.out.println("You entered "+x);
       } catch(InputMismatchException e) {
           System.out.println("This is an invalid entry, please enter an integer");
       }
   }
}

SAMPLE I/Os:

Input:

42

Output:

You entered 42

Input:

Alex

Output:

This is an invalid entry, please enter an integer


Related Solutions

Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java...
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java * description of class Driver here. *these is the main class where it acts like parent class. Compiler will execute firstly static method. import java.util.Scanner; public class Driver {     public static void main (String[] args){         Scanner stdIn = new Scanner(System.in);         String user;         String computer;         char a = 'y';         do {             System.out.println("What kind of Computer would you like?");...
1) Describe briefly what exceptions are and what their purpose is. What is the try block?...
1) Describe briefly what exceptions are and what their purpose is. What is the try block? What is the catch block? What happens with the flow of control if the catch block does not catch a thrown exception? Give a simple example. 2) Describe briefly what templates are and what their purpose is. 3) Write one line of code for each line below. What is the template type in each case? - Create a vector to store student IDs -...
In-Class coding exercise: (try - catch) (pass / fail) The purpose of this in-class coding exercise...
In-Class coding exercise: (try - catch) (pass / fail) The purpose of this in-class coding exercise is to simulate various exception conditions using the program provided. package com.InClass; /* * This program demonstrates the ability of catching different types of exceptions" * You will have to modify the method() codes to trigger various/different exceptions. * inClass Coding ( you will have to remove (comment out) the previous error condition before moving to trigger the next) * 1) throw a myExcept...
Instead of using int.TryParse, use int.Parse instead and use try/catch in C# to handle possible errors...
Instead of using int.TryParse, use int.Parse instead and use try/catch in C# to handle possible errors using System; using System.Collections.Generic;                    public class Program {    public static void Main()    {        List<int> list = new List<int>();               Console.WriteLine("Please input integers: (in one line)");                      string input = Console.ReadLine();        string[] tokens = input.Split(); // split string into tokens "12 13 10" -> "12" "13"...
Exercise 2: Try-Catch Exercise Write a Java code that does the following: Create a class MyClass...
Exercise 2: Try-Catch Exercise Write a Java code that does the following: Create a class MyClass and create three methods myMethod1(), Method2() and Method3(). Invoke Method2() from Method1() and Method3() from Method2(). Write a code that can throw an exception inside myMethod3() and compile: File file=new File("filename.txt"); Scanner sc=new Scanner(file); You will get compilation errors now, as you are not handling a checked exception FileNotFoundException. Declare throws over myMethod3() and myMethod2(). You will need to add throws FileNotFoundException on myMethod()...
Find the readData() method Inside this method is a try block without any catch statements. Add...
Find the readData() method Inside this method is a try block without any catch statements. Add the following 5 catch statements to this file (Hint: put them in the right order): RuntimeException Exception FileNotFoundException NumberFormatException InputMismatchException For each of these print out a short message describing the exception that occurred Java Class import java.io.File; import java.io.FileNotFoundException; import java.util.InputMismatchException; import java.util.Scanner; public class ReadInData {    public static double readData(String fileName) {        File file = new File(fileName);       ...
How does try/catch(exception) processing help resolve run time exceptions? What is a custom exception? What are...
How does try/catch(exception) processing help resolve run time exceptions? What is a custom exception? What are it's benefits? What does it mean when we raise a custom exception?
IN PYTHON Your task this week is to use loops to both validate user input as...
IN PYTHON Your task this week is to use loops to both validate user input as well as automate a test suite for your lab solution from last week. Your program will prompt the user for the cost of their groceries. Then you are to calculate the value of the coupon to be awarded based on the amount of the grocery bill. Use the table below to determine coupon amounts. Money Spent   Coupon Percentage Less than $10   0% From $10...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will enter...
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2....
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT