数组计数器不适用于java

时间:2016-07-23 16:31:03

标签: java arrays netbeans indexoutofboundsexception

我正在制作一个使用JOptionPane几天的Java程序。我不是在谈论约会(2016年10月14日等),而是几天:Sunday, Monday等等。

我的问题是在当天添加特定天数的功能(例如今天是星期二,然后再添加5天)。

我正在使用数组访问/引用特定日期以进行显示和输出。

我引用星期日到星期六,数组索引分别为0到6。

问题在于,假设当天是星期六,如果用户在其中添加了3天,则程序崩溃。

我相信这会崩溃,因为星期六位于索引6,并且算法尝试访问第9个索引,该索引不存在。由于Java是一种安全的语言,它不显示“null”,而是决定崩溃。

在这种情况下应该发生的事情是,从星期六开始,该节目将在星期二显示,而不是:

  

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:9

我使用Netbeans作为我的IDE,我自学java,因为我的大学教我c ++,visual basic,c#for my year and course。如果你想要细节,那么,

这是主类的源代码:

package weekdaysprogram;

import java.util.*;

public class weekdayParametersProgramMain 
{

    static Scanner console = new Scanner (System.in);

    public static void main(String[] args) 
    {
        weekdayParametersProgram firstObject = new weekdayParametersProgram();
        firstObject.inputMainMenu();
    }
}

以下是第二节课的源代码:

package weekdaysprogram;

import javax.swing.JOptionPane;

public class weekdayParametersProgram
{
    int currentDay; //variable used for referencing a certain day

    String[] day = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; //Array of days

    public void inputMainMenu() //Main menu function
    {
        int choice;

        String inputStr;
        String mainMenuStr = "Day Class\n"
                + "Enter choice: \n"
                + "1. Set Day \n"
                + "2. Print Day \n"
                + "3. Print Next Day \n"
                + "4. Print Previous Day \n"
                + "5. Calculate Day \n"
                + "6. Exit";

        inputStr = JOptionPane.showInputDialog(mainMenuStr);
        choice = Integer.parseInt(inputStr);

        switch (choice)
        {
            case 1:
                setDay();
                break;
            case 2:
                printDay();
                break;
            case 3:
                printNextDay();
                break;
            case 4:
                printPreviousDay();
                break;
            case 5:
                calculateDay();
                break;
            case 6:
                exit();
                break;
            default:
                JOptionPane.showMessageDialog(null, "Error Try Again", "Error", JOptionPane.ERROR_MESSAGE);
                inputMainMenu();
                break;
        }
    }


    public void calculateDay() //the 5th function I'm getting an error at aka the culprit of my error
    {
        String message = "Current Day: " + currentDay + " - " + day[currentDay] + "\n"
                + "Please enter the amount of days to be added: ";

        int tempNum1 = currentDay;
        String tempNum2 = JOptionPane.showInputDialog(message);
        int tempNum3 = Integer.parseInt(tempNum2);

        for (int count=0; count <= tempNum3; count++)
        {
            if (count == 7) tempNum1 = 0;
            else if (count==0) continue; //this is a patch, since there would be a confusion if the user inputted 1 for the addtional day
            else tempNum1++;
        }

        String nextMessage = day[currentDay] + " + " + tempNum3 + " days = " + day[tempNum1];

        JOptionPane.showMessageDialog(null, nextMessage, "New Day", JOptionPane.INFORMATION_MESSAGE);

        inputMainMenu();
    }

    public void setDay() //1st function for set day
    {

        String inputStr;

        String message = "Enter day index: \n"
                + "0 = " + day[0] + "\n"
                + "1 = " + day[1] + "\n"
                + "2 = " + day[2] + "\n"
                + "3 = " + day[3] + "\n"
                + "4 = " + day[4] + "\n"
                + "5 = " + day[5] + "\n"
                + "6 = " + day[6] + "\n";
        inputStr = JOptionPane.showInputDialog(message);

        switch (inputStr)
        {
            case "0":
                currentDay = 0;
                break;
            case "1":
                currentDay = 1;
                break;
            case "2":
                currentDay = 2;
                break;
            case "3":
                currentDay = 3;
                break;
            case "4":
                currentDay = 4;
                break;
            case "5":
                currentDay = 5;
                break;
            case "6":
                currentDay = 6;
                break;
            default:
                JOptionPane.showMessageDialog(null, "Please try again.", "Error", JOptionPane.ERROR_MESSAGE);
                setDay();
                break;
        }

        inputMainMenu();
    }

    public void printDay() //2nd function for printing out the current day
    {
        JOptionPane.showMessageDialog(null, day[currentDay], "Current Day", JOptionPane.INFORMATION_MESSAGE);

        inputMainMenu();
    }

    public void printNextDay() //3rd function for printing out the next day
    {
        int tempNum = currentDay;

        if (tempNum == 6) tempNum = 0;
        else tempNum += 1;

        JOptionPane.showMessageDialog(null, day[tempNum], "Next Day", JOptionPane.INFORMATION_MESSAGE);

        inputMainMenu();
    }

    public void printPreviousDay() //4th function for printing out the previous day
    {
        int tempNum = currentDay;

        if (tempNum == 0) tempNum = 6;
        else tempNum -= 1;

        JOptionPane.showMessageDialog(null, day[tempNum], "Previous Day", JOptionPane.INFORMATION_MESSAGE);

        inputMainMenu();
    }

    public void exit()
    {
        System.exit(0);
    }
}

3 个答案:

答案 0 :(得分:3)

而不是

    for (int count=0; count <= tempNum3; count++)
    {
        if (count == 7) tempNum1 = 0;
        else if (count==0) continue; //this is a patch, since there would be a confusion if the user inputted 1 for the addtional day
        else tempNum1++;
    }

你可以使用

tempNum1 = (currentDay + tempNum3) % 7;

%是模运算符,因此结果将始终在0到6之间。

答案 1 :(得分:0)

calculateDay()方法中,某些输入的执行可能会失败。

  • 如果用户输入“6”,tempNum3将是整数6。
  • 在for循环中,count将从0开始并循环到tempNum3,即6。
  • 对于从1到6的计数值,tempNum1每次都会递增。
  • tempNum1初始化为currentDay(也可能是6),tempNum1的值大于6,当{String} IndexOutOfBoundsException时{1}}已建成。

编辑: Loris的回答还提供了一个解决方案(使用模运算符),我建议您每次更改nextMessage数组的索引时都这样做。 (但要小心负值)

答案 2 :(得分:0)

问题出在calculateDay()方法

让我们逐行讨论您的代码。

在输入currentDay=5方法

之前设想calculateDay()

现在仔细阅读代码中的评论

    String message = "Current Day: " + currentDay + " - " + day[currentDay] + "\n"
            + "Please enter the amount of days to be added: ";//here currentDay =6

    int tempNum1 = currentDay;//tempNum1=6
    String tempNum2 = JOptionPane.showInputDialog(message);//suppose input "3"
    int tempNum3 = Integer.parseInt(tempNum2);//tempNum3 = 3

    for (int count=0; count <= tempNum3; count++)
    {
        if (count == 7) tempNum1 = 0;
        else if (count==0) continue; 
        else tempNum1++;//for count value 1,2,3 tempNum1 will increase so it will be 7, 8 finally 9. So tempNum1=9
    }

    String nextMessage = day[currentDay] + " + " + tempNum3 + " days = " + day[tempNum1];//here tempNum1=9 So ArrayIndexOutOfBound occurs

要避免此错误,请添加其他检查,就像您在其他方法中所做的那样

    JOptionPane.showMessageDialog(null, nextMessage, "New Day", JOptionPane.INFORMATION_MESSAGE);


        for (int count=0; count <= tempNum3; count++)
        {
            if (count == 7) tempNum1 = 0;
            else if (count==0) continue; 
            else {
                tempNum1++

                if(tempNum1=7) tempNum=0;
            }
        }