Question

Exception handling to detect input String vs. Integer

6.6 LAB: Exception handling to detect input String vs. Integer

The given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. The program fails and throws an exception if the second input on a line is a String rather than an Integer. At FIXME in the code, add a try/catch statement to catch java.util.InputMismatchException, and output 0 for the age.

Ex: If the input is:

Lee 18
Lua 21
Mary Beth 19
Stu 33
-1

then the output is:

Lee 19
Lua 22
Mary 0
Stu 34


2 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Scanner;
import java.util.InputMismatchException;

public class NameAgeChecker {
   
   public static void main(String[] args) {
      
      Scanner scnr = new Scanner(System.in);
      
      String inputName;
      int age;
      
      inputName = scnr.next();
      
      while (!inputName.equals("-1")) {
         
         try {
            
            age = scnr.nextInt();
            
         }
         catch (InputMismatchException ex) {
            
            age = -1;
            scnr.nextLine();
            
         }
         
         System.out.println(inputName + " " + (age + 1));
         inputName = scnr.next();
         
      }
      
   }
   
}


Add a comment
Answer #2

# Split input into 2 parts: name and age

parts = input().split()

name = parts[0]

while name != '-1':

    # FIXME: The following line will throw ValueError exception.

    #        Insert try/except blocks to catch the exception.

     try:

        age = get_age()

        heart_rate = fat_burning_heart_rate(age)

        print('Fat burning heart rate for a {:d} year-old: {:.1f} bpm'.format(age, heart_rate))

        

    except age = 0

        age = int(parts[1]) + 1

        print('{} {}'.format(name, age))

    

    # Get next line

    parts = input().split()

    name = parts[0]

Add a comment
Know the answer?
Add Answer to:
Exception handling to detect input String vs. Integer
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
  • In C++ Please The given program reads a list of single-word first names and ages (ending...

    In C++ Please The given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. The program fails and throws an exception if the second input on a line is a string rather than an int. At FIXME in the code, add a try/catch statement to catch ios_base:: failure, and output o for the age. Ex: If the input is: Lee 18 Lua 21 Mary Beth 19 Stu 33...

  • Java Question, I need a program that asks a user to input a string && then...

    Java Question, I need a program that asks a user to input a string && then asks the user to type in an index value(integer). You will use the charAt( ) method from the string class to find and output the character referenced by that index. Allow the user to repeat these actions by placing this in a loop until the user gives you an empty string. Now realize that If we call the charAt method with a bad value...

  • Write a Java program that inputs a list of integer values in the range of −...

    Write a Java program that inputs a list of integer values in the range of − 1 to 100 from the keyboard and computes the sum of the squares of the input values. This program must use exception handling to ensure that the input values are in range and are legal integers, to handle the error of the sum of the squares becoming larger than a standard Integer variable can store, and to detect end-of-file and use it to cause...

  • Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary.

    #In Coral  CHALLENGE ACTIVITY 7.1.1: Convert to binary.  Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is: As long as x is greater than e Output x % 2 (remainder is either e or 1) x= x / 2 Note: The above algorithm outputs the O's and 1's in reverse order. Ex: If the input is 6, the output is: 011 (6 in binary is 110; the...

  • Forms often allow a user to enter an integer. Write a program that takes in a string representing an integer as input, and outputs yes if every character is a digit 0-9.

     4.18 LAB: Checker for integer string Forms often allow a user to enter an integer. Write a program that takes in a string representing an integer as input, and outputs yes if every character is a digit 0-9. Exx If the input is: 1995 the output is: yes Ex If the input is: 42,000 1995! the output is no Hint: Use a loop and the Character isDigitO function. 418.1: LAB: Checker for integer string

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

  • Create a DataEntryException class whose getMessage() method returns information about invalid integer data. Write a program...

    Create a DataEntryException class whose getMessage() method returns information about invalid integer data. Write a program named GetIDAndAge that continually prompts the user for an ID number and an age until a terminal 0 is entered for both. If the ID and age are both valid, display the message ID and Age OK. Throw a DataEntryException if the ID is not in the range of valid ID numbers (0 through 999), or if the age is not in the range...

  • Assignment 11 – Exceptions, Text Input/Output - Random Numbers Revised 9/2019 Chapter 12 discusses Exception Handling...

    Assignment 11 – Exceptions, Text Input/Output - Random Numbers Revised 9/2019 Chapter 12 discusses Exception Handling and Input/Output. Using try/catch/finally statement to handle exceptions, or declare/throw an exception as needed, create the following program: Create an array of 25 random numbers between 0 & 250 formatted to a field width of 10 & 4 decimal places (%10.4f). Use the formula Math.random() * 250. Display the array of random numbers on the console and also write to a file. Prompt the...

  • In this assignment you are going to handle some basic input operations including validation and manipulation,...

    In this assignment you are going to handle some basic input operations including validation and manipulation, and then some output operations to take some data and format it in a way that's presentable (i.e. readable to human eyes). Functions that you will need to use: getline(istream&, string&) This function allows you to get input for strings, including spaces. It reads characters up to a newline character (for user input, this would be when the "enter" key is pressed). The first...

  • DatabaseFilter Design a DatabaseFilter class that will manage the file 1/O (input/output) of an employee ArrayList...

    DatabaseFilter Design a DatabaseFilter class that will manage the file 1/O (input/output) of an employee ArrayList object. For a Database Filter class to actually store an ArrayList object, it must know the file to which the list must be read from or written to. Note: It is expected that you may have more methods within your class design than requested in the specifications described below. However, your class should support at a minimum the following data and operations: encapsulated data...

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