0

I need help to understand the code.

public class ComputeLoanUsingInputDialog{
    public static void main(String[] args){
        String annulInterestRateString = JOptionPane.ShowInputDialog("Enter annual interest rate:")

        // convert string to double
        double annualInterestRate = Double.parseDouble(annualInterestRateString);

        //Obtain monthly interest rate
        double monthlyInterestRate = annualInterestRate/1200;

        .....
    }
}

So my question is if you have a dialog box pop out to ask user to insert a number then why do you need to use parse method to convert the variable from string to double?

mpromonet
  • 11,326
  • 43
  • 62
  • 91
Misha
  • 133
  • 5
  • 15
  • Because all input in java is in the form of a `String` – Extreme Coders Apr 26 '13 at 01:37
  • There's a lot of different ways to achieve what you want. You could take a look at [this](http://stackoverflow.com/questions/14783836/joptionpane-and-reading-integers-beginner-java/14784096#14784096) for some ideas.. – MadProgrammer Apr 26 '13 at 01:41

4 Answers4

1

Because Java accepts the input as a String - it doesn't that what it's getting is a double until you tell it to parse that String into a double.

drew moore
  • 31,565
  • 17
  • 75
  • 112
  • This is my first time here posting, didn't aware of the format, thank you for fixing it for me – Misha Apr 26 '13 at 02:02
  • Thank you drewmore, I appreciated your help and I am glad that I came here, it helps a lot! – Misha Apr 26 '13 at 02:26
1

Because it's much easier to manipulate a double mathematically than it is a string.

You get an annual interest from the dialog box as a string, you can see this from the online documentation (all but one returns a String, the one that returns an Object doesn't match your function signature).

However, you can't really do much with that other than string-type operations.

If you want to manipulate it mathematically (such as dividing it by twelve hundred in your case), it needs to be converted into a numeric type of some description.

Now you could modify JOptionPane to provide:

double JOptionPane.ShowInputDialogGetDouble (...);

but that introduces a large amount of new code (one per type) with lots of extra error checking that is, honestly, unnecessary since you can do it quite easily with your current method, Double.parseDouble().

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

Because JOptionPane.showInputDialog() returns String, since the user is free to type non-digit characters in the text field.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0

JOptionPane returns a String object as it's return value

http://docs.oracle.com/javase/6/docs/api/javax/swing/JOptionPane.html#showInputDialog(java.awt.Component, java.lang.Object)

(Can't get the url to show up as a single link, you'll have to copy the whole thing.

If the return type was double, you wouldn't have to parse it.

amarunowski
  • 103
  • 2
  • 9