View Single Post
  #1 (permalink)  
Old 11-04-2008, 12:26 AM
Hunkpapa Hunkpapa is offline
Member
 
Join Date: Oct 2008
Posts: 2
Rep Power: 0
Hunkpapa is on a distinguished road
Default [SOLVED] Extracting Tokens Help
Hello. I'm stuck on something and could use some help...

I'm trying to gather numbers from a user and provide a sum, using a StringTokenizer class to extract the input. I've written the below code which compiles without incident, but crashes when I run it with the following errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1,2,3"
at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1224)
at java.lang.Double.parseDouble(Double.java:482)
at SumOfNumbers.main(SumOfNumbers.java:24)


Can someone take a look and help me get back on track? Thanks.

Code:
import javax.swing.JOptionPane;
import java.util.StringTokenizer;

public class SumOfNumbers
{
	public static void main(String[] args)
	{
		String input;			// User input
		double sum = 0.0;		// Accumulator
		
		// Get a list of numbers.
		input = JOptionPane.showInputDialog("Enter a series of " + 
		                      "numbers separated only by commas: ");
		
		
		// Convert string to numeric data and assign to variable.							 
		sum = Double.parseDouble(input);
		
		// Create a StringTokenizer object.
		StringTokenizer strtok = new StringTokenizer(input, ",");
		
		// Get the numbers and sum them.
		while (strtok.hasMoreTokens())
		{
			input = strtok.nextToken();
			sum += Double.parseDouble(input);
			sum++;
		}
		
		// Display the sum.
		JOptionPane.showMessageDialog(null, "The sum of those " + 
		                              "numbers is " + sum);

		// Exit the applicaton.
		System.exit(0);
	}	
}
Reply With Quote