簡體   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