1

The output is taking count, name, income and then again income according to the number of counts and then shows outOfBound error for the count.

Here is the code -

public class Main { // Tax Calculator App

    public static long calculateTax(long income1){
        long tax = 0;
        if (income1 >= 300000) {
            tax = income1 * 20 / 100;
        } else if (income1 >= 100000 && income1 < 300000) {
            tax = income1 * 10 / 100;
        } else if (income1 < 100000) {
            tax = 0;
            System.out.println("Tax Amount = 0 ");
        }

        return tax;
    }

    public static void main(String[] args) {

        System.out.println("Tax Calculator App");
        System.out.println("-----WELCOME-----");

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter total person count: ");
        int count = sc.nextInt();
        sc.nextLine();

        String[] pName = new String[count];
        long[] pIncome = new long[count];
        System.out.println("Enter the name: ");

        for (int i = 0; i <= count; i++) {
            pName[i] = sc.nextLine();
            System.out.println("Enter the income: ");
            }for (int i = 0; i <= count; i++) {
                  pIncome[i] = sc.nextLong();
                  sc.nextLine();
                  long tax = 0;
                  System.out.println("Name: " + pName + "Tax: " + tax);
                  }
    }
}
Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
Prem22
  • 13
  • 5

2 Answers2

0

You are using a <= (less than or equals) operator in your for loop. This mean it will reach the person count and attempt to index the pName array by the count.

For example, say the count is 1, the array will be initialized with a size of 1, and it'll access pName[0], then pName[1], which is out of bounds, as the size is one.

You're also referencing the entire array in the printed result, you should be indexing to get the person's name.

Revised code for you is here: https://replit.com/@viomckinney/SOHelp#Main.java (Note: Indentation is not perfect as I just did a quick copy)

  • Thanks, I understood the ArrayOutOfBound error problem. But it's still not repeating the loop after the first person's inputs, instead it is asking to give the income according to number of counts. – Prem22 Aug 13 '21 at 10:17
0

As @Violet McKinney and @Henry Twist were saying, your array is out of bounds because of the =. Also, after updating the loop I checked your output is missing the name. The outcome was a java object.

On your last part of the code:

for (int i = 0; i < count; i++) {
            pIncome[i] = sc.nextLong();
            sc.nextLine();
            long tax = 0;
            System.out.println("Name: " + pName[i] + "Tax: " + tax);
        }

pName => pName[i]

Alex Susanu
  • 163
  • 1
  • 9