Start with the code below and complete the getInt method. The method should prompt the user to enter an integer. Scan the input the user types. If the input is not an int, throw an IOException; otherwise, return the int. In the main program, invoke the getInt method, use try-catch block to catch the IOException.
import java.util.*;
import java.io.*;
public class ReadInteger {
pubilc static void main() {
// your code goes here }
public static int getInt() throws IOException {
// your code goes here }
}
CODE :
import java.util.*; import java.io.*; public class ReadInteger { public static void main(String[] args) { try { int a = getInt(); System.out.println(a+" is an integer."); } catch (IOException e) { System.out.println("IOException called!"); } } public static int getInt() throws IOException { Scanner sc= new Scanner(System.in); System.out.println("Enter an integer: "); if(sc.hasNextInt()){ int num=sc.nextInt(); return num; } else{ throw new IOException("exception") ; } } }
EXAMPLES:
1.
2.
Get Answers For Free
Most questions answered within 1 hours.