Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

User input int x, if not int throw exception, if int then output x

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading