Home Ask Login Register

Developers Planet

Your answer is one click away!

jkjk February 2016

Only accept non-negative numbers Java

else if (bb.equals("Dollar") && cc.equals("Pound")){
        input = JOptionPane.showInputDialog("What amount would you like to convert?:");
        double aa = Double.parseDouble(input);
        double output =(aa*rate);
        JOptionPane.showMessageDialog(null, String.format("Your amount is: $%.2f",  output));

How do I make this so that if someone enters a negative number a message will popup saying invalid input?

Answers


mohammedkhan February 2016

I assume the number you're checking to see if it's positive is defined by the variable aa? Personally I prefer using BigDecimal when it comes to dealing with monetary values, in which case I would do:

BigDecimal aa = null;
try {
    aa = new BigDecimal(input);
} catch (NumberFormatException nfe) {
    //Not a numerical value, throw an error
}
if (aa.compareTo(BigDecimal.ZERO) <= 0) {
    //Value is negative
}

Post Status

Asked in February 2016
Viewed 1,183 times
Voted 13
Answered 1 times

Search




Leave an answer


Quote of the day: live life