Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What is parse? (Double.parseDouble();)?  RSS feed

 
Natasha Reaney
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

I am taking an Introduction to Java course. We are using the D. Liang's text, which so far is pretty clear. However, whenever I read my professor's examples I get confused because he uses code I have never seen before. This may be a silly question but what does Double.parseDouble() do in the following code? This is an example he gave. I pasted the whole code just in case.

public static void main(String[] args) {
Scanner keyboard;
keyboard = new Scanner(System.in);
boolean userContinue = true;
String userInput;
int count = 0;
double sum = 0;
double average = 0;
while (userContinue)
{
System.out.println("Enter a number or Q to quit");
userInput = keyboard.next();
if (userInput.toLowerCase().equals("q"))
{
userContinue = false;
}
else
{
sum += Double.parseDouble(userInput);
count += 1;
}
} // end of the while
average = sum / count;
System.out.printf("The average is %f\n", average);
} // end of main

Thank you!!
Natasha
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
API on parseDouble():

Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.


What happens in your code is that user is prompted to enter a number that is stored as a String in userInput variable. Since you want to operate with the value entered as with a number (calculate the sum), you get double value represented as userInput String by using mentioned method (bolded part of your code). E.g.



Edit: And please UseCodeTags (<-click) when posting your code.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!