0

I would like the code to catch the error when the user enters a string instead of an integer. You can see I have tried a try catch block which is still not working. Everything else is perfect apart from that. How can I solve this?

Here is how the output should be:

Welcome to the Squares and Cubes table

Enter an integer: five
Error! Invalid integer. Try again.
Enter an integer: -5
Error! Number must be greater than 0
Enter an integer: 101
Error! Number must be less than or equal to 100
Enter an integer: 9

Number  Squared Cubed
======  ======= =====
1       1       1
2       4       8
3       9       27
4       16      64
5       25      125
6       36      216
7       49      343
8       64      512
9       81      729

Continue? (y/n): y

Enter an integer: 3

Number  Squared Cubed
======  ======= =====
1       1       1
2       4       8
3       9       27

Here is the code:

import java.util.InputMismatchException;
import java.util.Scanner;

public class cube2 {

    public static void main(String[] args)
    {
        // Welcome the user
        System.out.println("Welcome to the Squares and Cubes table");
        System.out.println();

        Scanner sc = new Scanner(System.in);
        String choice = "y";

        do
        {
            // Get input from the user
            System.out.print("Enter an integer: ");
            int integer = sc.nextInt();


                 try {

                    break;
                }
                catch (NumberFormatException e) {
                    System.out.println("Error! Invalid integer. Try again.");
                }



            System.out.print("Enter an integer: ");
            integer = sc.nextInt();  





             if(integer<0){

                System.out.println("Error! Number must be greater than 0");
                System.out.print("Enter an integer: ");
                integer = sc.nextInt();

            }

             if(integer>100){

                System.out.println("Error! Number must be less than or equal to 100");

                System.out.print("Enter an integer: ");
                integer = sc.nextInt();
            }

            // Create a header
            String header = "Number  " + "Squared " + "Cubed   " + "\n"
                        +   "======  " + "======= " + "=====   ";
            System.out.println(header);

            int square = 0;
            int cube = 0;

            String row = "";
            for (int i = 1; i <= integer; i++)
            {

                square = i * i;
                cube = i * i * i;

                row = i + "       " + square + "       " + cube;
                System.out.println(row);
            }

            // See if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();

        }
        while (!choice.equalsIgnoreCase("n"));  
    }
}
khelwood
  • 46,621
  • 12
  • 59
  • 83
denim
  • 49
  • 7
  • There is nothing in the `try` block - why do you use it then? – Nico Haase Nov 01 '18 at 12:30
  • 1
    Your code makes no logical sense. `try` is used to run exception sensitive code and catch the exception if it arises ... your sensitive code is ___outside___ of that `try` block and you only run the command `break` in there, which won't fail/throw an exception. Oracle provides tutorials, you should follow them: https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html – Tom Nov 01 '18 at 12:34
  • @Nico Haase is there another way I can go about it without using a try catch block – denim Nov 01 '18 at 12:39
  • @ Tom I will go through the tutorials right away. Appreciated. – denim Nov 01 '18 at 12:39
  • You should then also read: [Validating input using java.util.Scanner](https://stackoverflow.com/a/3059367/3824919) – Tom Nov 01 '18 at 12:46

4 Answers4

1

Integer.parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type.

It should be like this:

    System.out.print("Enter an integer: ");
    Scanner sc =new Scanner(System.in);

    try {
        int integer = Integer.parseInt(sc.nextLine());
    } catch (NumberFormatException e) {
        System.out.println("Error! Invalid integer. Try again.");
    }
Hülya
  • 3,054
  • 2
  • 10
  • 16
1

I changed your code a little bit and posted it as a whole, to avoid confusion:

public static void main(String[] args) {
    // Welcome the user
    System.out.println("Welcome to the Squares and Cubes table");
    System.out.println();
    Scanner sc = new Scanner(System.in);
    String choice = "y";

    do {
        int integer = Integer.MAX_VALUE;
        while (integer == Integer.MAX_VALUE) {
            // Get input from the user
            System.out.print("Enter an integer: ");
            String input = sc.nextLine();
            try {
                integer = Integer.parseInt(input);
            }
            catch (NumberFormatException e) {
                System.out.println("Error! Invalid integer. Try again.");
            }
        }
        if(integer<0){

            System.out.println("Error! Number must be greater than 0");
            System.out.print("Enter an integer: ");
            integer = sc.nextInt();

        }

        if(integer>100){

            System.out.println("Error! Number must be less than or equal to 100");

            System.out.print("Enter an integer: ");
            integer = sc.nextInt();
        }

        // Create a header
        String header = "Number  " + "Squared " + "Cubed   " + "\n"
                +   "======  " + "======= " + "=====   ";
        System.out.println(header);

        int square = 0;
        int cube = 0;

        String row = "";
        for (int i = 1; i <= integer; i++)
        {

            square = i * i;
            cube = i * i * i;

            row = i + "       " + square + "       " + cube;
            System.out.println(row);
        }

        // See if the user wants to continue
        System.out.print("Continue? (y/n): ");
        choice = sc.next();
        System.out.println();

    } while (!choice.equalsIgnoreCase("n"));
}

The idea was to make another while inside your loop and run it until a user passes an integer.

Schidu Luca
  • 3,607
  • 1
  • 10
  • 25
1

You could use this method just to test if the entered value is a valid integer. Base the outcome of this you can start with your other validation

public boolean isInt(string input) {
    try {
      Integer.parseInt(text);
      return true;
    } catch (NumberFormatException e) {
     return false;
     } 
    }
Jephren Naicker
  • 300
  • 2
  • 16
-2

Use this getInput(scanner); method to get the input from user. This will handle the exception and recursively calls itself till the user enters the number.

public static int getInput(Scanner sc) {
    int integer=0;
    try {
        System.out.print("Enter an integer: ");

        integer = Integer.parseInt(sc.nextLine());
    }       
    catch (Exception e) {
        System.out.println("Error! Invalid integer. Try again.");
        getInput( sc);
    }

    return integer;
}

Call to this function will be like int integer = getInput(sc);

After this modification, your code will looks like,

public class cube2 {

    public static int getInput(Scanner sc) {
        int integer=0;
        try {
            System.out.print("Enter an integer: ");

            integer = Integer.parseInt(sc.nextLine());
        }       
        catch (Exception e) {
            System.out.println("Error! Invalid integer. Try again.");
            getInput( sc);
        }

        return integer;
    }

    public static void main(String[] args)
    {
        // Welcome the user
        System.out.println("Welcome to the Squares and Cubes table");
        System.out.println();

        Scanner sc = new Scanner(System.in);
        String choice = "y";

        do
        {


            int integer = getInput(sc); // To get the Numeric input from Console

            if(integer<0){

                System.out.println("Error! Number must be greater than 0");
                System.out.print("Enter an integer: ");
                integer = sc.nextInt();

            }

            if(integer>100){

                System.out.println("Error! Number must be less than or equal to 100");

                System.out.print("Enter an integer: ");
                integer = sc.nextInt();
            }

            // Create a header
            String header = "Number  " + "Squared " + "Cubed   " + "\n"
                    +   "======  " + "======= " + "=====   ";
            System.out.println(header);

            int square = 0;
            int cube = 0;

            String row = "";
            for (int i = 1; i <= integer; i++)
            {

                square = i * i;
                cube = i * i * i;

                row = i + "       " + square + "       " + cube;
                System.out.println(row);
            }

            // See if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.nextLine();
            System.out.println();

        }
        while (!choice.equalsIgnoreCase("n"));  
    }
}

In your code choice = sc.next(); was changed in to choice = sc.nextLine();

Output :

Welcome to the Squares and Cubes table

Enter an integer: 9
Number  Squared Cubed   
======  ======= =====   
1       1       1
2       4       8
3       9       27
4       16       64
5       25       125
6       36       216
7       49       343
8       64       512
9       81       729
Continue? (y/n): y

Enter an integer: hi
Error! Invalid integer. Try again.
Enter an integer: hello
Error! Invalid integer. Try again.
Enter an integer: 5
Number  Squared Cubed   
======  ======= =====   
Continue? (y/n): y

Enter an integer: 12
Number  Squared Cubed   
======  ======= =====   
1       1       1
2       4       8
3       9       27
4       16       64
5       25       125
6       36       216
7       49       343
8       64       512
9       81       729
10       100       1000
11       121       1331
12       144       1728
Continue? (y/n): 
  • You call `getInput( sc);` in the exception block without doing anything with the value returned by that recursive call. How is your code supposed to return anything else then the initial value "0" once it entered the exception branch? – Tom Nov 01 '18 at 13:27
  • Even if this code did work, it's not good practice to use recursion for something easily solved *without* recursion. It deserves a down-vote, if only to warn the person asking the question and future visitors to check the other answers for better solutions. – Hovercraft Full Of Eels Nov 01 '18 at 19:28