1
votes

I want the user to enter integers into an array. I have this loop I wrote which has a try and catch in it, in case a user inserts a non integer. There's a boolean variable which keeps the loop going if is true. This way the user will be prompted and prompted again.

Except, when I run it, it gets stuck in a loop where it repeats "Please enter # " and "An Integer is required" without letting the user input a new number. I reset that number if an exception is caught. I don't understand.

import java.util.*;
public class herp
{
    //The main accesses the methods and uses them.
    public static void main (String[] args)
    { 
        Scanner scan = new Scanner(System.in);
        System.out.println("Hello and welcome!\n");
        System.out.print("This program stores values into an array"+" and prints them.\n");
        System.out.println("Please enter how many numbers would like to store:\n");
        int arraysize = scan.nextInt();

        int[]   mainarray = new int[arraysize+1];
        int     checkint  = 0;
        boolean notint    = true;
        int     prompt    = 1;

        while (prompt < mainarray.length)
        {
            // Not into will turn true and keep the loop going if the user puts in a
            // non integer. But why is it not asking the user to put it a new checkint?
            while(notint)
            {
                try
                {
                    notint = false;
                    System.out.println("Please enter #"+ prompt); 
                    checkint = scan.nextInt();
                } 
                catch(Exception ex)
                {
                    System.out.println("An integer is required." + 
                                       "\n Input an integer please"); 
                    notint   = true;
                    checkint = 1;
                    //See, here it returns true and checkint is reset.
                }      
            }
            mainarray[prompt] = checkint;
            System.out.println("Number has been added\n");
            prompt++;
            notint = true;
        }
    } 
}
2
Has scan been initialized? You could very much be getting a NullPointerException on scan. Your catch statement is too broad, narrow it down to what you want to catch or it will hide bugs in your code.initramfs
Scan has been initialized, yes, I'll update the code.munchschair
Try printing the stack trace for your exception, it might not be what you expect. Also, try catching NumberFormatException for what you seem to need.webuster
Gnargh, and there goes our formatting. PLEASE don't ovverride edits ;)Johannes H.
BTW, class should really be named Herp, convention is to always use uppercase :DJohannes H.

2 Answers

4
votes

Once the scanner has thrown an InputMismatchException it cannot continue to be used. If your input is not reliable, instead of using scanner.nextInt() use scanner.next() to obtain a String then convert the string to an int.

Replace:

checkint = scan.nextInt();

With:

String s = scan.next();
checkint = Integer.parseInt(s);
0
votes

I have corrected it like below. I don't rely on exception, but check if the next Scanner input is int (using hasNextInt()). If not int, just consume Scanner token and wait for the next user input. Looks like it is working, apart from 0 being inserted as a first array element, because you started indexing prompt from 1.

public class Herp {

    //The main accesses the methods and uses them.
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Hello and welcome!\n");
        System.out.print("This program stores values into an array" + " and prints them.\n");
        System.out.println("Please enter how many numbers would like to store:\n");
        int arraysize = scan.nextInt();

        int[] mainarray = new int[arraysize + 1];
        int checkint = 0;
        boolean notint = true;
        int prompt = 1;

        while (prompt < mainarray.length) {
            while (notint) {
                notint = false;
                System.out.println("Please enter #" + prompt);
                // check if int waits for us in Scanner
                if (scan.hasNextInt()) {
                    checkint = scan.nextInt();
                } else {
                    // if not, consume Scanner token
                    scan.next(); 
                    System.out.println("An integer is required."
                        + "\n Input an integer please");
                    notint = true;
                }
            }
            mainarray[prompt] = checkint;
            System.out.println("Number has been added\n");
            prompt++;
            notint = true;
        }

        for (int i : mainarray) {
            System.out.print(i + " ");
        }
    }
}