简体   繁体   English

java.lang.ArrayIndexOutOfBoundsException?

[英]java.lang.ArrayIndexOutOfBoundsException?

I am currently teaching my self some basic Java through a text book and gave myself a "homework problem" but I'm having difficulty when writing to a .txt file of a method. 我目前正在通过教科书教我自己一些基本的Java,并给自己一个“作业问题”但是我在写一个方法的.txt文件时遇到了困难。 It doesn't want to take more than 2 people. 它不想超过2人。 Here's a quick run down of what the method is meant to do: 以下是该方法的简要说明:

1.) Collects the number of people the user would like to enter into the data file 1.)收集用户想要输入数据文件的人数

2.) Collects the first and last name of each person in a two-dimensional array 2.)在二维数组中收集每个人的名字和姓氏

3.) Collects a number of payments set by the user for each (separate) person that the user entered into an array. 3.)收集用户为用户输入数组的每个(单独)人设置的多个付款。

4.) Then it calculates the average payment for each of the people entered into another array(so each person should have their own average) 4.)然后它计算进入另一个阵列的每个人的平均付款(因此每个人应该有他们自己的平均值)

5.) Lastly, it writes the data to a .txt file named "BusinessData.txt." 5.)最后,它将数据写入名为“BusinessData.txt”的.txt文件。

It seems to be working perfectly up until it tries to write more than 2 people into the .txt file. 它似乎完全正常工作,直到它尝试将超过2个人写入.txt文件。 It's driving me nuts and I really would like to know how to fix this before moving on to the next couple of topics. 这让我疯狂,我真的想知道如何解决这个问题,然后继续讨论下几个主题。

Here's the error message that I am getting when I try to add more than 2 people: 这是我尝试添加超过2个人时收到的错误消息:

Exception in thread "main" java.lang.Array IndexOutofBoundsException: 3 线程“main”中的异常java.lang.Array IndexOutofBoundsException:3
at Business1.dataCollect(Business1.java:210) 在Business1.dataCollect(Business1.java:210)
at Business1.main(Business1.java:62) 在Business1.main(Business1.java:62)

I'd greatly appreciate any tips. 我非常感谢任何提示。

Here's the actual code: 这是实际的代码:

import java.util.*;
import java.io.*;

public class Business1
{
    public static void main(String[] args) throws IOException
    {
        // Declare local variables
        int menuChoice;

        // Declare local objects
        Scanner input = new Scanner(System.in);

        // Display the program title
        System.out.println("\n\n\n\n\t\t\t\t***************************************\n"
                                +  "\t\t\t\t* Average Customer Payment Calculator *\n"
                                +  "\t\t\t\t***************************************\n\n\n");

        // Start of a do-while loop: Continues the program as long as the user doesn't choose to exit
        do
        {
            // Start of a do-while loop: Input Validation (menuChoice must be between 1 - 4)
            do
            {

                // Prompt user for menuChoice
                System.out.print("\tPlease enter an integer in accordance to the given choices:\n\n"
                                 + "\t(1) Collect and Erase Old Data\n"
                                 + "\t(2) Read Saved Data\n"
                                 + "\t(3) Append Old Data\n"
                                 + "\t(4) Exit Program\n\n"
                                 +"\tEnter Choice: ");

                menuChoice = input.nextInt();
                System.out.println("\n\n");


                // If menuChoice is equal to 1: Erase old Data and Collect and Write new data
                if(menuChoice == 1)
                {
                    try
                    {
                        dataCollect();
                    }

                    catch(IOException e)
                    {
                        System.out.println("Error");
                    }
                }
                // else if menuChoice is equal to 2: Read Saved Data
                else if(menuChoice == 2)
                {

                } 
                // else if menuChoice is equal to 3: Append Old Data
                else if(menuChoice == 3)
                {

                }
                // else if menuChoice is equal to 4: Exit Program
                else if(menuChoice == 4)
                {
                    System.out.println("\n\n\n\t\tGoodbye!\n\n\n");
                }

                // else display error message: Error. Please enter a number 1 - 4 
                else
                {
                    System.out.println("\n\nERROR. Please enter a number 1 - 4\n\n");
                }

            // End of do-while loop: Input Validation (menuChoice must be between 1 - 4)
            } while(menuChoice < 1 || menuChoice > 4);
        // End of a do-while loop: Continues the program as long as the user doesn't choose to exit
        } while(menuChoice != 4);
    }

    // Create a method named dataCollect
    public static void dataCollect() throws IOException
    {
        // Declare local variables
        int numPeople, numPayments /* array size for payments */;
        double totalPayments = 0, averagePayment;
        double [] paymentsArray  /* different payments */, averagePaymentsArray;
        String [][] namesArray /* First name, last name in array */;

        // Declare objects
        Scanner keyboard = new Scanner(System.in);


        // Prompt user for the number of people they would like to add to the records and store in variable numPeople
        System.out.print("\tHow many people would you like to add to your records?\n\n\tEnter an integer: ");
        numPeople = keyboard.nextInt();
        System.out.println("\n\n");

        // Initialize arrays
        namesArray = new String[numPeople][2];


        // Create a counter for the for-loop
        int count = 0;
        // For-loop will prompt user for first and last name of each person
        for(int i = 1; i <= numPeople; i++)
        {

            // Consume the remaining newline character
            keyboard.nextLine();

            // Prompt user for first name
            System.out.print("\tPlease enter the FIRST name of person #" + i  +": ");
            namesArray[count][0] = keyboard.nextLine();
            System.out.println("\n\n");

            //Prompt user for last name
            System.out.print("\tPlease enter the LAST name of person #" + i + ": ");
            namesArray[count][1] = keyboard.nextLine();
            System.out.println("\n\n\n");

            count++;
        }

        // Reset counter for the next for-loop
        count = 0;
        int count2 = 1; // Used to keep track of which payment number the user is inputing
        int count3 = 0; 
        int count4 = -1;


        // ****************************************************************
        // * Open file for input ******************************************
        // ****************************************************************

        PrintWriter outputFile = new PrintWriter("BusinessData.txt");
        outputFile.println("\t\t\tBusiness Data\n\n");
        outputFile.println("First Name\tLast Name\tP 1\t\tP 2\t\t P 3\t\tAverage Payments\n\n"
                        +  "------------------------------------------------------------------------------------------------------------------------------------------------------\n");

        // For-loop will ask for number of payments each person made while also collecting the value of each of those payments in a nested for-loop.
        for(int i = 0; i < numPeople; i++)
        {
            // Prompt user for first name
            System.out.print("\tPlease enter the number of payments made by " + namesArray[count][0] +" " + namesArray[count][1] + "(Put in 3 for now) : ");
            numPayments = keyboard.nextInt();


            System.out.println("\n\n");

            // Initialize array then reset it for the next person to come
            paymentsArray = new double[numPayments];

                for(int j = 0; j < numPayments; j++)
                {
                    // ****************************************************************
                    // * Open file for input ******************************************
                    // ****************************************************************

                    System.out.print("\n\n\tPlease enter payment value of payment #" + count2 + " that " + namesArray[count][0] +" " + namesArray[count][1] + " made: $");
                    paymentsArray[j] = keyboard.nextDouble();
                    System.out.println("\n\n");

                    // Increment counter
                    count2++;
                }

                    // ************************************************************************
                    // * Calculating Average Payment ******************************************
                    // ************************************************************************

                    // For loop for calculating average
                    for(int k = 0; k < numPayments; k++)
                    {
                        totalPayments += paymentsArray[k];
                    }

                    // Calculate the Average Payment
                    averagePayment = totalPayments/paymentsArray.length;

                    /**************************************************
                     ********** BUG LIES IN THE WRITING  **************
                    ***************************************************/


                    // nested for-loop will write data now otherwise it'll just be wiped out and overwritten by the next input
                    for(int l = 1; l < numPeople; l++)
                    {   

                        // Increment counter4
                        count4++;
                        // Output first name
                        outputFile.print(namesArray[count4][count3]);

                        // Increment counter3
                        count3++;

                        // Output last name
                        outputFile.print("\t\t" + namesArray[count4][count3] + "\t\t");
                        // Reset counter3
                        count3 = 0;


                        for (int m = 0; m < numPayments; m++)
                        {
                            outputFile.print(paymentsArray[m] + "\t\t");
                        }

                        outputFile.println(averagePayment + "\n\n");
                    }


             // Reset total Payments for the next iteration
            totalPayments = 0.0;

            // Increment the counter
            count++; 
        }
        outputFile.close();

    // End of dataCollect method
    }   

Running your code gives me Exception for 3+ users. 运行代码为3+用户提供了Exception。 ArrayIndexOutOfBoundsException thrown at 引发的ArrayIndexOutOfBoundsException

  outputFile.print(namesArray[count4][count3]);

Running in debug mode shows that namesArray[count4][count3] is pointing to a value which is not available . 在调试模式下运行表明namesArray [count4] [count3]指向一个不可用的值。

count4 is incremented to out of bounds value because of the below loop. 由于以下循环,count4增加到超出边界值。

I don't undertstand why you need this loop 我不知道为什么你需要这个循环

for(int l = 1; l < numPeople; l++)
                { 
enter code here}

If you remove this it works fine. 如果你删除它,它工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM