Search code examples
javaarraystry-catchnumberformatexception

Try & Catch in double Array not working as I expected


I'm trying to perform a try catch on a user input and place the user input into an array if it passes the check but if I enter an invalid input, it would replace that index with 0 and move onto the next index. I'm trying to figure out how to get a reprompt to work inside the for loop so that the invalid value in that particular index gets replaced with a valid user input. The order of the values in the array doesn't matter. I'm trying to do this without importing other Java libraries!

I would very much appreciate any help ! I'm new to programming and Java. Thank you for your time !

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

Solution

  • 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;
    }