-2

I am working on a Java program that determines Evens, Odds, and Negative numbers from 12 inputted integers.

It then separates them into different arrays. The course I am following suggests building an exception handler and I utilized the Try-Catch Method for the Exception error I may receive.

It then creates an Out of Bounds error for counting these numbers when I enter a String.

I've commented on the area in which I have trouble reprompting the user. So far, I've tried prompting at the error with twelveInt [i] = in.nextInt(); and just in.next();.

Why is the program affected outside of the loop?

Here is the program:

public static void main(String[] args){
    Scanner in = new Scanner(System.in);
          
    int [] twelveInt = new int [12];
          
    int countEven = 0;
          
    int countOdd = 0;
          
    int countNeg = 0;
    
    boolean ehandle = true;
   

    for (int i = 0; i < twelveInt.length; i++) {
        while(ehandle){
            try{
                System.out.println("Enter the #" + (i + 1) + " integer.");
                twelveInt [i] = in.nextInt();
                ehandle = false;
            }
            catch(Exception e){
                System.out.println("Please enter integers only");
                // Unsure of what to add here to handle the errors and allow me to reprompt. in.next(); 
                //does not work nor does twelveInt [i] = in.nextInt();
            }
            if (twelveInt[i] % 2 == 0){
                countEven++;
            }
            if (twelveInt[i] % 2 != 0){
                countOdd++;
            }
            if (twelveInt[i] < 0){
                countNeg++;
            } 
        }
    }
        
    int [] evens = new int [countEven];    
    int [] odds = new int [countOdd];
    int [] negatives = new int [countNeg];
    
    countEven = 0;
    countOdd = 0;
    countNeg = 0;
        
    
    for (int i : twelveInt) {
        if (i % 2 == 0){
            evens[countEven++] = i;
        }
        if (i % 2 != 0){
            odds[countOdd++] = i;
        }
        if (i < 0){
            negatives[countNeg++] = i;
        }          
    }
              
    System.out.println("Here are the Even numbers you entered");
    System.out.println(Arrays.toString(evens));
          
    System.out.println("Here are the Odd numbers you entered");
    System.out.println(Arrays.toString(odds));
          
    System.out.println("Here are the Negative numbers you entered");
    System.out.println(Arrays.toString(negatives));
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • You just 2 hours ago [asked](https://stackoverflow.com/questions/71274200/compilation-error-at-enhanced-for-loop-i-is-already-defined-in-main-method-but) this question. Why didn't u edit that post with this question? – Sync it Feb 26 '22 at 07:33
  • @Syncit This one deals with an exception handler. I thought it would be appropriate to create a new question? I'm fairly new to all of this. – hello_world Feb 26 '22 at 07:35
  • You could have written your questions in that post as 2 points. This will mostly be marked as duplicate as your code here is literally the same there – Sync it Feb 26 '22 at 07:38
  • If you want to reiterate your `while(ehandle)` loop when you get an exception, put `continue` in your catch block. But you should set `ehandle` back to true at the top of your for-loop. – khelwood Feb 26 '22 at 07:39
  • @khelwood Thank you for your answer. Where would I set ehandle back to true? Could you maybe put this comment in the form of an answer in my program? – hello_world Feb 26 '22 at 07:45
  • @Syncit Editing a previous answered question to add a new question into it is not appropriate, and such edits are typically reverted. – khelwood Feb 26 '22 at 07:49

2 Answers2

0

The problem in your code is that after you run your loop and enter your first number, you then define ehandle = false.

This means that you never enter the rest of your loop since you exit the while loop. Therefore, you never increment the values of countEven, countOdd, or countNeg.

This results in an error because when you try running this line: int [] evens = new int [countEven]; , countEven is still 0, so you get an error when you try to iterate it.

To avoid this error, you can modify your try catch error as so:

import java.util.*;
import java.io.*;
class Main {
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
          
    int [] twelveInt = new int [12];
          
    int countEven = 0;
          
    int countOdd = 0;
          
    int countNeg = 0;
                 
    
          
    for (int i = 0; i < twelveInt.length; i++) {
        System.out.println("Enter the #" + (i + 1) + " integer.");
        boolean error = true;
        while (error) {
            try {
              twelveInt [i] = in.nextInt();
              if (twelveInt[i] % 2 == 0){
                  countEven++;
              }
              if (twelveInt[i] % 2 != 0){
                  countOdd++;
              }
              if (twelveInt[i] < 0){
                  countNeg++;
              } 
              error = false;
            } 
            catch (Exception e) {
              System.out.println("Please enter integers only");
              in.next();
            }
        }
    }
    
    int [] evens = new int [countEven];    
    int [] odds = new int [countOdd];
    int [] negatives = new int [countNeg];
        
    
    countEven = 0;
    countOdd = 0;
    countNeg = 0;
    
        
    
    for (int i : twelveInt) {
            if (i % 2 == 0){
                evens[countEven++] = i;
            }
            if (i % 2 != 0){
                odds[countOdd++] = i;
            }
            if (i < 0){
                negatives[countNeg++] = i;
            }          
        }
              
    System.out.println("Here are the Even numbers you entered");
    System.out.println(Arrays.toString(evens));
          
    System.out.println("Here are the Odd numbers you entered");
    System.out.println(Arrays.toString(odds));
          
    System.out.println("Here are the Negative numbers you entered");
    System.out.println(Arrays.toString(negatives));
  }
}

We first try taking in the user input, and if we get an exception error, we will use the catch so our code does not terminate. NOTE: we must do in.next() otherwise we will get an infinite loop (since integers leave a trailing newline, resulting in infinite exceptions).

I hope this helped! Please let me know if you need any further clarifications or details :)

Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
  • Thank you so much! This did work. However, I still don't understand the changes too well. From my understanding, you basically defined the boolean inside of the for loop, then when the program runs, if there are numbers entered, it doesn't mind and proceeds with the loop by setting the exception handler boolean to false. If letters are entered, then the catch portion reprompts with `in.next();`? – hello_world Feb 26 '22 at 08:04
  • You're on the right track! Basically, for every iteration through ```twelveInt```, we enter a while loop that can only be broken out of once ```error = false```, which is accomplished once the code runs smoothly. However, if there is an error, then we go into the catch block of the code, where we output an error message and reset the loop. The way that integers in Java work with newlines is that they leave behind a trailing newline. This means when we take in another integer, it will "absorb" that newline and give an error since it's a String. To avoid this loop, we use ```in.next()```. – Aniketh Malyala Feb 26 '22 at 08:19
  • Does that answer your question ^ ? (I ran out of characters sorry) – Aniketh Malyala Feb 26 '22 at 08:19
  • I am probably going to sleep now, so if you want me to clarify further I will answer tomorrow :) goodnight! – Aniketh Malyala Feb 26 '22 at 08:20
0

If you want to reiterate your while(ehandle) loop when you get an exception, you can put continue in your catch block. But you should set ehandle back to true at the top of your for-loop.

for (int i = 0; i < twelveInt.length; i++) {
    ehandle = true;
    while (ehandle) {
        try {
            System.out.println("Enter the #" + (i + 1) + " integer.");
            twelveInt[i] = in.nextInt();
            ehandle = false;
        } catch(Exception e) {
            System.out.println("Please enter integers only");
            continue;
        }
        ...
khelwood
  • 55,782
  • 14
  • 81
  • 108