Need Help Catching An ArrayIndexOutOfBoundsException On A For Each Loop (Java)

66 views Asked by At

HW3.java

import java.util.Scanner;

public class HW3 {

//Method Establishes Scanner For Inputing Hour
public static int Scanner() {
    Scanner x = new Scanner(System.in);
    int pay = x.nextInt();
    return pay;
}
        
public static void main(String args[]) {
    //Asks For Hour Input, Input Hours Into Variable
    System.out.println("Input Hours");
    int hour = Scanner();

    //Establish Array Of Employees With Name And Wage Categories
    Employee [] employee = new Employee[4];
    employee [0] = new Employee("Shinji Ikari", 15.50);     
    employee [1] = new Employee("Rei Ayanami", 21.35);  
    employee [2] = new Employee("Asuka Langley Soryu", 2.12);
    employee [3] = new Employee("Kaworu Nagisa", 20.01);
    
    //For Loop Running The showText Method From Employee.java For Each Employee In Array 
    try {
        for (Employee e : employee)     
            e.showText(hour);       
    } catch(ArrayIndexOutOfBoundsException oob) {
        System.out.println("NO");
    }   
}   

}

Employee.java

public class Employee {

//Sets Private Variables That Defines "Employee"
private String name;
private double wage;
private double totalpay;

    //Employee Constructors For Name And Wage
    public Employee(String employeename, double hourlypay) {
        name = employeename;
        wage = hourlypay;
    }   
    
    //Returns The Name Value        
    public String getName() {           
        return name;        
    }
    
    //Sets ASnd Updates Name
    public void setName(String ename) {         
        name = ename;   
    }       
    
    //Returns The Wage Value
    public double getWage() {
        return wage;
    }
    
    //Sets And Updates Wage
    public void setWage(double hourlypay) {
        wage = hourlypay;
    }
    
    //Method That Subtracts A 30% Tax From Base Hourly Pay  
    public double getTotalPay() {       
        totalpay = wage - (wage*0.3);
        return totalpay;
            }

    //Method Takes Name, Wage, and Totalpay From Employee.java Alongside Hour From HW3.java To Place Them In The Printed Statement
    public void showText(int hoursworked) {
        try {System.out.printf("The employee " +name+ ", who earns $%.2f per hour, worked for " +hoursworked+ " hours last week and took home $%.2f after taxes.\n", wage, getTotalPay()*hoursworked);
        } catch(ArrayIndexOutOfBoundsException oob) {
            System.out.println("Error");
        }
    }

}

In this weekly paycheck estimator program I need to catch a possible ArrayIndexOutOfBoundsException when extracting an employee from my employee array. I have no idea how to test if my current placement of the exception program is correct because I don't know how to format an each loop to attempt to loop beyond the four employees I currently have in my main method. Is my current exception program placed correctly in the loop or do I need to place it somewhere else?

1

There are 1 answers

0
Stephen C On

You cannot catch an exception if it isn't thrown. The try / catch statements would catch ArrayIndexOutOfBoundsException if it was thrown ... but it isn't thrown.

try {
    System.out.printf("The employee " + name + 
         ", who earns $%.2f per hour, worked for " +
         hoursworked + 
         " hours last week and took home $%.2f after taxes.\n", 
         wage, getTotalPay() * hoursworked);
} catch (ArrayIndexOutOfBoundsException oob) {
    System.out.println("Error");
}

The code inside the code block is not operating on an array at all, so the exception cannot be thrown.

(Aside: the printf is misguided too. You are using both string concatenation and formatting. You can do it all with just formatting, and the code will be a lot more readable.)

try {
    for (Employee e : employee)     
        e.showText(hour);       
} catch (ArrayIndexOutOfBoundsException oob) {
    System.out.println("NO");
}

This is operating on the array, but it is doing it in a way that is guaranteed to not go beyond the bounds of the array.

If you wanted the above cause that exception (so that you can catch it) you could rewrite the loop like this:

try {
    for (int i = 0; i < 9999; i++) // this loop is deliberately wrong    
        employee[i].showText(hour);       
} catch (ArrayIndexOutOfBoundsException oob) {
    System.out.println("NO");
}

Now you will get an exception when i is 4. But you wouldn't / shouldn't do that in a real program. You should avoid using exception handling to implement "normal" control flow. (Though what "normal" control flow means is open to interpretation!)


Is the code correct?

Yes and no; see above.

  • Yes because you would catch the exception if it was thrown. And this code does compile.
  • No because the exception won't be thrown. Guaranteed. Code that tries to catch an (unchecked) exception that cannot be thrown is redundant and misleading ... and therefore wrong.