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);
}
} |