11.8 lab: exception handling to detect input string vs. integer

I need to write code where the program fails and throws an exception if the second input on a line is a String rather than an Integer. I am confused as to how to compare if the input is a string or an int and I am also struggling on how to use a try/catch statement.

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")) {
     // FIXME: The following line will throw an InputMismatchException.
     //        Insert a try/catch statement to catch the exception.
     age = scnr.nextInt();
     System.out.println(inputName + " " + (age + 1));
     
     inputName = scnr.next();
  }

}

asked Apr 13, 2021 at 23:44

1

Instead of

age = scnr.nextInt();

Try

try {
    age = scnr.nextInt();
    System.out.println(inputName + " " + (age + 1));
}
catch(InputMismatchException e) {
    System.out.println("Please enter a valid integer");
}

sorifiend

5,7921 gold badge30 silver badges43 bronze badges

answered Apr 13, 2021 at 23:50

LuckyBandit74LuckyBandit74

4271 gold badge3 silver badges10 bronze badges

2.14 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 try and except blocks to catch the ValueError exception 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

11.8 lab: exception handling to detect input string vs. integer

Transcribed Image Text:G entry level * Home Content zy Section 2.14 X (229) ITS12 X G 2.14 LAB: E X b Answered: * (Solved] In Contact Us M Inbox (7,71 × + i learn.zybooks.com/zybook/CYB_135_54915392/chapter/2/section/14 = zyBooks My library > CYB/135: Object-Oriented Security Scripting home > 2.14: LAB: Exception handling to detect input string vs. integer E zyBooks catalog ? Help/FAQ Kenneth Schultz - then the output is: Lee 19 Lua 22 Mary 0 Stu 34 346682.2019644.gx3zgy7 LAB 2.14.1: LAB: Exception handling to detect input string vs. integer 0/ 10 АCTIVITY main.py Load default template.. 1 # Split input into 2 parts: name and age 2 parts = input().split()| 3 name = parts[0] 4 while name != '-1': # FIXME: The following line will throw ValueError exception. Insert try/except blocks to catch the exception. age = int(parts[1]) + 1 print('{} {}'.format(name, age)) 7 8 9 10 # Get next line parts = input().split() name = parts[0] 11 12 Run your program as often as you'd like, before submitting for grading. Below, type any needed input values in the first box, then click Run program and observe the program's output in the second box. Develop mode Submit mode Enter program input (optional) Lee 18 6:05 AM O Type here to search 75°F Rain to stop 9/16/2021

11.8 lab: exception handling to detect input string vs. integer

11.8 lab: exception handling to detect input string vs. integer

11.8 lab: exception handling to detect input string vs. integer

Q: 12.5 LAB: EXception handling to detect Input string Vs. Integer The given program reads a list of…

A: Since no programming language is mentioned, I am using python. Algorithm: Start Declare an empty…

Q: 20.8 LAB: Exception handling to detect input string vs. integer   The given program reads a list of…

A: The Answer is in below Steps

Q: Program 4 Write a programmer defined function to find the perimeter of circle. Add a decorator…

A: As per our guidelines, we are supposed to answer only one question. Kindly repost the remaining…

Q: Program 3 Write a programmer-defined function to find the area of circle. Add a decorator function…

A: The question is to write python code for the given problem.

Q: Program 3 Write a programmer-defined function to find the area of circle. Add a decorator function…

A: Algorithm: Start Implement a decorator function Error_Handler() which raises an exception if the…

Q: Program 6 Use nested (or inner) functions, closure and decorators to write menu driven program to…

A: import math def decorator(radius, choice):                         # decorator function     if…

Q: 1.(A)Wite a C++ program containing a possible exception. Use a try block to throw it and a catch…

A: According to our guidelines, we are supposed to answer only 1 question. So I am answering the first…

Q: T/F 5) If an exception occurs in a catch phrase, then the violation class matches. For instance, if…

A: please see the next step for solution

Q: T/F 5) If an exception occurs in a catch phrase, then the violation class matches. For instance, if…

A: Given that,  If an exception occurs in a catch phrase, then the violation class matches. For…

Q: This is in C++ The given program reads a list of single-word first names and ages (ending with -1),…

A: Purpose of the solution: The exception handling statements should be added to the given C++ program…

Q: Python please: Write a program that reads the integers user_index_num and user_element_value as…

A: lst = [1,2,3,4]        try:        user_index_num = input()    user_element_value = input()     if…

Q: Write Java code to show an example of using a complete try-catch statement. Include actual code that…

A: Hey there, I am writing the required solution based on the above given question. Please do find the…

Q: C++ by using Exception(throw, try, catch), validate a grade. ask the user to enter a grade and then…

A: logic:- use throw keyword within try block to catch exception and message of your own choice.…

Q: Exercise # 2 Write a program that asks the user to input a set of floating-point values. When the…

A: Click to see the answer

Q: The given program reads a list of single-word first names and ages (ending with -1), and outputs…

A: According to the information given:- We have to create python program in that we can take user input…

Q: The given program reads a list of single-word first names and ages (ending with -1), and outputs…

A: Program Plan:  Prompt for the string.  Split the string and filter it on the basis of string and…

Q: The given program reads a list of single-word first names and ages (ending with -1), and outputs…

A: I used here as a example - Ex: If the input is: Lee 18 Lua 21 Mary Beth 19 Stu 33 -1 then the output…

Q: The given program reads a list of single-word first names and ages (ending with -1), and outputs…

A: According to the Question below the Solution:   Output:

Q: The given program reads a list of single-word first names and ages (ending with -1), and outputs…

A: Program code: # Split input into 2 parts: name and ageparts = input().split()#namename = parts[0]#if…

Q: The given program reads a list of single-word first names and ages (ending with -1), and outputs…

A: PROGRAM CODE:   #include <iostream>#include <vector>using namespace std; int main() {…

Q: The given program reads a list of single-word first names and ages (ending with -1), and outputs…

A: To handle the exception we use try/catch statement, for example try{    statements to be executed…

Q: he following line, allows C++ to throw an exception whenever the failbit is set.…

A: #include<iostream> #include<limits> using namespace std; int main() { int a;…

Q: 1. Write a java program to display the A) Arithmetic exception. B) Array bounds exception. C)…

A: As per out guidelines we are supposed to answer only one question. Kindly repost other questions as…

Q: The following line, allows C++ to throw an exception whenever the failbit is set. |…

A: Algorithm :  doubleIt function Step 1 : using cin.exceptions() to throw an exception. Step 2 :…

Q: **12.20 (Remove package statement) Suppose you have Java source files under the direc- tories…

A: Programming approach Importing the required packages in the program. Obtain the file path as…

Q: PYTHON: Given a main program that searches for the ID or the name of a student from a dictionary,…

A: Given: PYTHON: Given a main program that searches for the ID or the name of a student from a…

Q: T/F 2) Anywhere in the software an exception is raised, the programme terminates

A: Given that, Anywhere in the software an exception is raised, the programme terminates.

Q: Create a code for a fuel milage calculator in C# code should include - Exception handling should…

A: given data  Create a code for a fuel milage calculator in C# code should include - Exception…

Q: Write a programmer-defined function to find the area of circle. Add a decorator function to validate…

A: Algorithm: Start Implement a decorator function named decorator_func() which checks the validity of…

Q: PYTHON CODE Write a function that takes a single number as an argument: 1) This function…

A: Python Code to check if the number is even(without using exception handling): def enterNum(num):…

Q: Python Code: Write a function that takes a single number as an argument: 1) This function…

A: Python: Parameters and arguments are simply the various terms used for the variables/values you're…

Q: 2. Create a program of your own choice and show a. The use of try-catch-finally block for exception…

A: a) The use of try-catch-finally block for exception handling.  class Main {  public static void…

Q: The following program has a function getint() that gets input from the input box and converts it to…

A: The above question python code is:

Q: 6.10) Write a program to model a simple calculator. Each data line should consist of the next…

A: Calculator.py  import math  print "+","add"  print "- ","substract"  print "*","multiply"  print…

Q: In c++, by using exception(throw, try, catch), validate a grade. Ask the user to enter a grade and…

A: #include <iostream> using namespace std; int main(){      int grade;    try {   //now reading…

Q: (6) Write a python program that asks the user for two filenames and calls your function…

A: def copy_even_files(string1, string2):        #Open string2 in write mode        fout =…

Q: in c++ Suppose a function toe throws a std::overflow_error exception. Put a call to toe in a…

A: An exception is a runtime error that arises during the execution of a program. In C++ to handle…

Q: 9. Write a program for function overloading - define int function ADDint ( Int x, Int y ) Return x+y…

A: int add(int x, int y){    return x + y;} This trivial function provides two integers and returns an…

Q: Q6/ A: Write a program that reads three issues and arranges them in a differential order? B: Write…

A: Note: As per our company guidelines, we are supposed to answer only one question. Kindly repost…

Q: 12.6 LAB: Fat-burning heart rate Write a program that calculates an adult's fat-burning heart rate,…

A: Here in coding questions language is not given so we write the code in c.…

Q: 5.22 In Python: Write a program whose input is two integers and whose output is the two integers…

A: Define the functions to swap the values. Declaring the variables including a temporary variable…

Q: The given program reads a list of single-word first names and ages (ending with -1), and outputs…

A: split() returns list and the value at index 0 will be name and value at index 1 to be parsed to age

Q: Exercise 1: Ask for a birthday, a favorite gift, and their dream job is and display that information…

A: Since programming language was not  mentioned  so, I chosen PYTHON . I have  provided  PYTHON  CODE…

Q: C# question   The point at which an exception is thrown is called ..............

A: Question. The point at which an exception is thrown is called ..............

Q: 2- Write a program in c to read names from the file "name.txt", which include (10) names ,then range…

A: File handling is a programming method by using which we can perform tasks in the files during…

Q: Write a program using c++ oop that prompts the user to enter a length in feet and inches and outputs…

A: Given: Write a program using c++ oop that prompts the user to enter a length in feet and inches and…

Q: Question 11 Write a function called // Precondition: p1, p2 and p3 either point // to dynamically…

A: Code in C++  Input :::    #include<iostream> using namespace std; void allocate3(int* &p1,…

Knowledge Booster

Recommended textbooks for you

  • 11.8 lab: exception handling to detect input string vs. integer

    Database System Concepts

    ISBN:9780078022159

    Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan

    Publisher:McGraw-Hill Education

    11.8 lab: exception handling to detect input string vs. integer

    Starting Out with Python (4th Edition)

    ISBN:9780134444321

    Author:Tony Gaddis

    Publisher:PEARSON

    11.8 lab: exception handling to detect input string vs. integer

    Digital Fundamentals (11th Edition)

    ISBN:9780132737968

    Author:Thomas L. Floyd

    Publisher:PEARSON

  • 11.8 lab: exception handling to detect input string vs. integer

    C How to Program (8th Edition)

    ISBN:9780133976892

    Author:Paul J. Deitel, Harvey Deitel

    Publisher:PEARSON

    11.8 lab: exception handling to detect input string vs. integer

    Database Systems: Design, Implementation, & Manag...

    ISBN:9781337627900

    Author:Carlos Coronel, Steven Morris

    Publisher:Cengage Learning

    11.8 lab: exception handling to detect input string vs. integer

    Programmable Logic Controllers

    ISBN:9780073373843

    Author:Frank D. Petruzella

    Publisher:McGraw-Hill Education

  • 11.8 lab: exception handling to detect input string vs. integer

    Database System Concepts

    ISBN:9780078022159

    Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan

    Publisher:McGraw-Hill Education

    11.8 lab: exception handling to detect input string vs. integer

    Starting Out with Python (4th Edition)

    ISBN:9780134444321

    Author:Tony Gaddis

    Publisher:PEARSON

    11.8 lab: exception handling to detect input string vs. integer

    Digital Fundamentals (11th Edition)

    ISBN:9780132737968

    Author:Thomas L. Floyd

    Publisher:PEARSON

    11.8 lab: exception handling to detect input string vs. integer

    C How to Program (8th Edition)

    ISBN:9780133976892

    Author:Paul J. Deitel, Harvey Deitel

    Publisher:PEARSON

    11.8 lab: exception handling to detect input string vs. integer

    Database Systems: Design, Implementation, & Manag...

    ISBN:9781337627900

    Author:Carlos Coronel, Steven Morris

    Publisher:Cengage Learning

    11.8 lab: exception handling to detect input string vs. integer

    Programmable Logic Controllers

    ISBN:9780073373843

    Author:Frank D. Petruzella

    Publisher:McGraw-Hill Education