Question 4-2

Write a program that reads a line from the user and says ``ok'' if the user's line represents a valid integer, and ``bad'' otherwise.

Type something. -56a2
bad
Use Integer.parseInt(s), which converts the string s to an int; if the string isn't formatted correctly, the class method throws a NumberFormatException.
import csbsju.cs160.*;
public class Example {
    public static void main(String[] args) {



    }
}

Solution

import csbsju.cs160.*;
public class Example {
    public static void main(String[] args) {
        try {
            IO.print("Type something. ");
            Integer.parseInt(IO.readString());
            IO.println("good");
        } catch(NumberFormatException e) {
            IO.println("bad");
        }
    }
}

Back to Review for Quiz 4