尝试并捕获双数组无法正常工作

问题描述 投票:0回答:2

我正在尝试对用户输入进行尝试捕获,如果通过了检查,则将用户输入放入数组,但是如果我输入无效的输入,它将用0替换该索引并移至下一个索引。我正在尝试弄清楚如何让重新提示在for循环内工作,以便该特定索引中的无效值被替换为有效的用户输入。数组中值的顺序无关紧要。我正尝试在不导入其他Java库的情况下执行此操作!

非常感谢您的帮助!我是编程和Java的新手。感谢您的时间 !

public static double[] getAmount()
   {
      int MAX_NUM = 10;
      double[] numArray = new double[MAX_NUM];
      for (int i = 0; i < numArray.length;i++)
      {
         double numInput;
         do
         {
            try
            {
               numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amounts in $: "));
            }
            catch (NumberFormatException e)
            {
               numInput = MAX_NUM - 11;
            }
            if (numInput < 0 || numInput > 999999)
            {
               JOptionPane.showMessageDialog(null, "Error. Please enter valid amount in dollars");
               numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amount in $: "));
            }
            else
            {
               numArray[i] = numInput;
            }
          }
          while (numInput < 0 && numInput > 999999);
       }
       return numArray;      
    }
java arrays try-catch numberformatexception
2个回答
0
投票
public static double[] getAmount()
{
  int MAX_NUM = 10;
  double[] numArray = new double[MAX_NUM];
  int i = 0;
  while (i < numArray.length)
  {
     double numInput;

        try
        {
           numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amounts in $: "));
        }
        catch (NumberFormatException e)
        {
           numInput = MAX_NUM - 11;
        }
        if (numInput < 0 || numInput > 999999)
        {
           JOptionPane.showMessageDialog(null, "Error. Please enter valid amount in dollars");
           numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amount in $: "));
        }
        else
        {
           numArray[i] = numInput;
           i++;
        }
   }

   return numArray;
}

0
投票

这应该起作用:


public static double[] getAmount()
   {
      int MAX_NUM = 10;
      double[] numArray = new double[MAX_NUM];
      for (int i = 0; i < numArray.length;i++)
      {
         double numInput;
         do
         {
            try
            {
               numInput = Double.parseDouble(JOptionPane.showInputDialog("Enter amounts in $: "));
            }
            catch (NumberFormatException e)
            {
               numInput = MAX_NUM - 11;
            }
            if (numInput < 0 || numInput > 999999)
            {

               JOptionPane.showMessageDialog(null, "Error. Please enter valid amount in dollars");
            }
          }
          while (numInput < 0 || numInput > 999999);
          numArray[i] = numInput;
       }
       return numArray;      
    }
© www.soinside.com 2019 - 2024. All rights reserved.