【问题标题】:Reading JOptionPane input into array将 JOptionPane 输入读入数组
【发布时间】:2018-09-15 22:20:08
【问题描述】:
package javaapplication3;

import javax.swing.JOptionPane;

public class JavaApplication3 {


    public static void main(String[] args) {

        Double[] temp = new Double[7];
        String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturady"};


        int i = 0;
        while (i <= days.length){

            temp[i] = Double.parseDouble(JOptionPane.showInputDialog("Please enter " + days[i] + "'s temperature in Fahrenheit."));


            i++;
        }

    }
}

我正在尝试将用户的输入读入临时数组,但在程序结束时出现 ArrayIndexOutOfBounds 错误。我的数组大小需要调整还是我发送的输入过多?

【问题讨论】:

  • days.length() -1
  • 记住,Java数组是0索引的,所以你可以引用0-6的位置

标签: java arrays loops input joptionpane


【解决方案1】:

您的“days”数组中有 7 个元素,因此创建了一个大小为 7 个元素的数组“temp”。但是在您的 while 循环中,您从索引 0 迭代到 7(8 次迭代!)并使用该索引 (while (i &lt;= days.length) {...) 访问 days 数组的元素。

所以最后你访问了你的 days 数组中索引为 7 的元素,但是由于数组索引从 0 开始,所以这个数组的最后一个索引是 6!

while (i < days.length) {...

应该修复你的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2011-03-08
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多