Results 1 to 3 of 3
Thread: [SOLVED] Extracting Tokens Help
- 11-03-2008, 11:26 PM #1
Member
- Join Date
- Oct 2008
- Posts
- 2
- Rep Power
- 0
[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.
Java 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); } }
- 11-03-2008, 11:48 PM #2
I assume that this is the statement at line 24:
sum = Double.parseDouble(input);
What does the API doc say for that method? IF it were smart enough to scanout the separate digits separated by commas,what would it do with all of them? It only returns a single value.
What happens if you take that statement out?
Why do you have that line there if you don't expect a double string?
If you are going to read in a String of digits sep by commas, then you must scan out the digits one by one before converting them to double.
- 11-04-2008, 01:17 AM #3
Member
- Join Date
- Oct 2008
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
Extracting JAR file
By Java Tip in forum Java TipReplies: 0Last Post: 02-08-2008, 09:17 AM -
Getting tokens using Scanner class
By Java Tip in forum Java TipReplies: 0Last Post: 02-05-2008, 09:11 AM -
tokens
By Gilgamesh in forum New To JavaReplies: 5Last Post: 12-02-2007, 11:30 PM -
How to use StringTokenizer for multiple tokens
By javaplus in forum New To JavaReplies: 2Last Post: 11-29-2007, 09:38 AM -
tokens
By Gilgamesh in forum New To JavaReplies: 3Last Post: 11-25-2007, 02:39 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks