繁体   English   中英

我在Java中的循环无法正常工作。 谁能看到原因?

[英]My loop in java is not working. Can anyone see why?

我即将进行编程实验。 我的程序在请求输入后要求输入停止。 我看不到我做错了什么。 谁能看到这个问题?

public static double dReadInputs(int numberOfInputs)        //this accepts and fills an array with grade inputs
{
    int t = 0;
    double[] inputs = new double[numberOfInputs];
    while (t < numberOfInputs)
    {
        JOptionPane.showInputDialog("Please enter 10 grade values one at a time: ");
        inputs[10] = Integer.parseInt(in.nextLine());
        t++;
    }
    return inputs[10];

inputs[10]的索引10引发异常,因为它可能大于inputs变量的大小。

这可能适用于您的情况:

inputs[t] = Integer.parseInt(in.nextLine()); 
public static double[] dReadInputs(int numberOfInputs)        //this accepts     and fills an array with grade inputs
{
    int t = 0;
    double[] inputs = new double[numberOfInputs];
    while (t < numberOfInputs)
    {
        JOptionPane.showInputDialog("Please enter "+numberOfInputs+"grade values one at a time: ");
        inputs[t] = Integer.parseInt(in.nextLine());
        t++;
    }
    return inputs;
}

基本上,您希望获得所有输入,因此要返回一个double数组,而不是一个double。 另外,请确保使用计数器(甚至更好的是创建一个for循环),以便更新double数组中的相应double。

发生的情况是,只有大小为10的数组时,您总是在写入数组中的第11个项目,因此它给出了ArrayOutOfBoundsException。

根据您对问题描述的理解。 您希望JOptionPane显示10次,并且每次接受输入并将其分配给数组。 见下文:

public static double[] dReadInputs(int numberOfInputs)       
    {
        int t = 0;
        double[] inputs = new double[numberOfInputs];
        while (t < numberOfInputs)
        {
            String in = JOptionPane.showInputDialog("Please enter value for grade " + (t + 1) + " : ");
            inputs[t] = Double.parseDouble(in);
            t++;
        }
        return inputs;
    }

您还可以保护代码免受可能的NullPointerException的影响 ,该异常可能在用户不提供输入并使用“ 取消”或“ 关闭”按钮关闭输入对话框时发生。 解:

if (in != null) {
  //inform user to enter valid +ve integer/double
  //you might wanna continue back to loop without incrementing t 
} 

您可以通过确保用户始终输入有效数字而不输入其他任何内容来保护代码免受NumberFormatException的侵害。 即使是空的输入对话框也会导致异常:解决方案:

try {
    inputs[t] = Double.parseDouble(in);
} catch(NumberFormatException nfe) {
  //inform user to input valid +ve integer/double
  //you might wanna continue back to loop without incrementing t
}

暂无
暂无

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

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