如何在对话框中从用户输入将数据值存储到数组中?

时间:2016-03-13 22:10:33

标签: java

import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class quiz
  public static void main(String[] args)
  {
    String name, allname, loopname;
    int names, allnames, op, loopsname;
    int arValues[];

    name = JOptionPane.showInputDialog(null, "Enter how many friends you have:");
    names = Integer.parseInt(name);
    arValues = new int[name-1];

**for(names = 0; names == names; names++)
{
  loopname = JOptionPane.showInputDialog(null, "enter your friend's names);
  loopsname = Integer.parseInt(loopsname);
  arValues[names] = loopsname;
}**

allname = JOptionPane.showInputDialog(null, "Enter the number of which friends name in which you want to see");
allnames = Integer.parseInt(allname);
op = arValues[allnames];

}

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

代码编译,但是当它运行时,它有多个运行时错误,包括超出范围。需要帮助搞清楚

错误消息:

java.lang.ArrayIndexOutOfBoundsException: 2 at quiz.main(quiz.java:28) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:27‌​2)

1 个答案:

答案 0 :(得分:1)

在for循环中,条件names == names始终为true。你应该做的是使用一个临时变量,比方说i,如下所示:

for (int i = 0; i < names; i++) {
    loopname = JOptionPane.showInputDialog(null, "Enter value for array:");
    loopsnames = Integer.parseInt(loopsnames);
    arValues[i] = loopsnames;
}

循环的每次迭代现在检查i以查看它是否小于names,如果为真,则递增它并在循环内运行代码。这可确保循环完全运行values次。导致错误的另一个地方是:

arValues = new int[names-1];

你应该做的:

arValues = new int[names];

因为您要准确保留names元素 以下是您的代码的完整且有效的版本:

import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class  quiz {
    public static void main(String[] args) {
        String name, allname, loopname;
        int names, allnames, op, loopsname;
        int arValues[];

        name = JOptionPane.showInputDialog(null, "Enter how many friends names you would like ot enter");
        names = Integer.parseInt(name);
        arValues = new int[value];

        for (int i = 0; i < names; i++) {
            loopname = JOptionPane.showInputDialog(null, "Enter your friend's name");
            loopnames = Integer.parseInt(loopname);
            arValues[i] = loopnames;
        }

        allname = JOptionPane.showInputDialog(null, "Enter the number of which friend you want to see");
        allnames = Integer.parseInt(allname);
        op = arValues[allnames];
    }

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