-1

I get the exception whenever I run the program without passing in the usDollarAmount or cancel the program... I'm using swing components to accept user input. The program works fine otherwise.

Please show me how to handle this... Thanks

THE Currency CALCULATOR
Exception in thread "main" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Currency.main(Currency.java:28)

import java.text.DecimalFormat;

import javax.swing.JOptionPane;

 public class Currency{

public static void main(String[] args)
{
    // declare and construct variables


    double usDollarAmount, poundsAmount,eurosAmount,rublesAmount;

    DecimalFormat twoDigits = new DecimalFormat("####.00");

    //print prompts and get input
    System.out.println("\tTHE Currency CALCULATOR");

    //print prompts and get input
    usDollarAmount = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter your dollar amount:"));


     // calculations

    poundsAmount = 0.64 * usDollarAmount;
    eurosAmount = 0.91 * usDollarAmount ;
    rublesAmount = 61.73 * usDollarAmount ;

     // output
  JOptionPane.showMessageDialog(null, "YOUR DOLLAR AMOUNT OF  " + twoDigits.format(usDollarAmount) + " is equal to  " + twoDigits.format(eurosAmount)  + " euros"  + " ," + twoDigits.format(poundsAmount)  + " pounds"  + " " + " and " + twoDigits.format(rublesAmount) + " rubles"  );


System.exit(0);

}

}

optimistic_creeper
  • 2,739
  • 3
  • 23
  • 37

1 Answers1

0

First assign the input to a variable and then do a null check. If not null do the parsing

String input = JOptionPane.showInputDialog(null, "Enter your dollar amount:");
if(input != null && !input.trim().isEmpty())
    usDollarAmount = Double.parseDouble();
  • @Pshemo mistake :D corrected – Thusitha Thilina Dayaratne Oct 14 '16 at 14:06
  • good point. I need to do a null check but that won't handle the exception thrown when a user click on the cancel button of the JOptionPane.showInputDialog. how do I write a code to exit the program when a user click on the cancel button? Thanks – user3561219 Oct 14 '16 at 15:01
  • Thanks Thusitha for pointing me in the right direction. This is how I handles the exception – user3561219 Oct 14 '16 at 18:28
  • String input = JOptionPane.showInputDialog(null, "Enter your dollar amount:"); if(input != null && !input.trim().isEmpty()){ usDollarAmount= Double.parseDouble(input); // calculations poundsAmount = 0.64 * usDollarAmount; eurosAmount = 0.91 * usDollarAmount ; rublesAmount = 61.73 * usDollarAmount ; } else { System.exit(0); } – user3561219 Oct 14 '16 at 18:28