gpt4 book ai didi

java - 如何将对话框中用户输入的数据值存储到数组中?

转载 作者:行者123 更新时间:2023-11-30 07:31:59 25 4
gpt4 key购买 nike

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)

最佳答案

在 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);
}
}

关于java - 如何将对话框中用户输入的数据值存储到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35976506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com