-5

Can someone give me a basic explanation of the purpose of parseDouble() in this code?

try{              
   // Change the billBeforeTip to the new input

   billBeforeTip = Double.parseDouble(arg0.toString());

   }

This code is from this tutorial. I didn't want to copy and paste the entire thing so I apologize if you have to refer to the link. Thanks for any help!

  • Have you read the [javadoc for that method](http://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#parseDouble-java.lang.String-)? – awksp Jul 03 '14 at 01:57
  • Yes but I don't understand the purpose of using it. I thought BillBeforeTip was already a Double. – David Grzyb Jul 03 '14 at 01:58
  • Yes, but `arg0.ToString()` (the thing you are parsing) isn't. – Michael Petrotta Jul 03 '14 at 02:00
  • That doesn't really have to do with the reason `parseDouble()` was used. Consider -- `arg0.toString()` is the wrong type to be assigned to `billBeforeTip`, right? So you need some way to make `billBeforeTip` the right type... – awksp Jul 03 '14 at 02:00
  • arg0 is a `CharSequence` that needs to be converted to a double, as `Double` doesn't have a `Double.parseDouble(CharSequence)` arg0 needs to be converted first to a `String` and then use `Double.parseDouble(String)` – morgano Jul 03 '14 at 02:01
  • That makes so much more sense, thank you! – David Grzyb Jul 03 '14 at 02:04

1 Answers1

4

To understand how this works you need to understand how public static void Main(String[] **args**) works.

Looking at: billBeforeTip = Double.parseDouble(arg0.toString()); We see that it attempts to parse a double from the first String passed in via the command line. If you were to turn your java application into a executable JAR it would run in the command prompt, then your code snippet you've provided would work successfully.

When you go to call the executable in the command prompt you can pass values into the args variable. Like so:

 loc\javaVersion -jar myJar.jar args[0] args[1] etc

After this runs your application would attempt to parse args[0] and turn it into a double.

Edit: Some IDE's allow you to pass in command line parameters which would allow you to debug your program and see how it would operate based on the passed in values.

Tdorno
  • 1,571
  • 4
  • 22
  • 32
  • So really all that the code is doing is parsing whatever args is? I understand that args is not a string so thats why its arg0.toString(); – David Grzyb Jul 03 '14 at 02:07
  • Everything passed via command line will come in as a `String`. Why it calls `.toString()` I do not know. Refer to [this](http://stackoverflow.com/questions/10312264/why-string-tostring) – Tdorno Jul 03 '14 at 02:09