i have to 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 Exception; otherwise, return the int. currently if you enter an int it doesnt print, and if u dotn enter an int it j throws a bunch of errors. ive seen ways online that use while loops but we havent done that yet in this course.
import java.util.Scanner;
public class Throwing
{
public static Scanner in = new Scanner( System.in );
public static void main(String[] args) throws Exception
{
int x = getInt();
System.out.println(x);
}
public static int getInt() throws Exception
{
System.out.println("enter an integer: ");
int x = in.nextInt();
in.close();
if (!in.hasNextInt());
{
throw new Exception("not an integer");
}
}
}
>Solution :
There are some problems in the getInt() method. It should be like this:
public static int getInt() throws Exception {
System.out.println("enter an integer: ");
if (!in.hasNextInt()) {
throw new Exception("not an integer");
} else {
int x = in.nextInt();
return x;
}
}
You should first check if the integer exists in the input stream with hadNextInt(), and then read it with nextInt(). Also delete the spurious semicolon in the line of the if statement.
Alternatively, if you don’t care about the exception class, just read the int with nextInt() and a java.util.InputMismatchException exception will be thrown for you if it isn’t an int.
public static int getInt() throws Exception {
System.out.println("enter an integer: ");
return in.nextInt();
}