Search code examples
javastringdoublejoptionpane

Converting double numerical value to text


In the following if statement from a loop in my code, if the given oldsalary[i] doesn't meet these guidelines, I want to restore the previous numerical value of oldsalary[i] to "Error". However I want it to stay as oldsalary[i] since I will be displaying all the oldsalary[i] later in my code.

So basically when all the oldsalary[i] are displayed in another loop, I want to be able to see "Error" so it's know that something was wrong with that value.

I know the way I have it is completely wrong, I just put it like this to make sense. Sorry if it doesn't make any sense.

if(oldsalary[i] < 25000 || oldsalary[i] > 1000000){

      JOptionPane.showMessageDialog(null, userinput[i]+"'s salary is not within 
      necessary limit.\n Must be between $25,000 and $1,000,000. \n If salary is 
      correct, empolyee is not eligible for a salary increase.");

      double oldsalary[i] = "Error";





        }

Solution

  • You can't store both the numerical value and an error indicator in a single double value.

    Your best bet is to wrap the salary as an object that contains both the salary value and a boolean that indicates the error condition:

    class Salary {
        private double value;
        private boolean error = false;
        ... constructor, getters and setters
    }
    

    And update your code to use the object instead. I.e.

    if(oldsalary[i].getValue() < 25000 || oldsalary[i].getValue() > 1000000) {
        oldsalary[i].setError(true);
        ...
    }
    

    So later you can do

    if (oldsalary[i].isError()) {
        // display error message
    }