reading doubles in a text file
I'm having problems get my program to read doubles in a text file and adding them up to be displayed to a user.
Any usggestions?
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Order1
{
public static void main(String[] arg)
throws FileNotFoundException
{
double sum = 0;
double price;
String output;
String str;
Scanner inFile =
new Scanner(new FileReader ("f:\\invoice.dat"));
while(inFile.hasNext())
{
price = inFile.nextDouble();
sum = sum + price;
inFile.nextDouble();
}
output = String.format("The total value of the items in the data file is $ %.2f", sum);
JOptionPane.showMessageDialog(null, output,
"File Totals",
JOptionPane.INFORMATION_MESSAGE);
inFile.close();
System.exit(0);
}
}
[901 byte] By [
Raziela] at [2007-10-2 13:42:34]

I redid the program and it is still not giving me the output I wanted.
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Order1
{
public static void main(String[] arg)
throws FileNotFoundException
{
double sum = 0;
double price = 0;
String output;
String str;
Scanner inFile =
new Scanner(new FileReader ("f:\\invoice.dat"));
while(inFile.hasNextDouble())
{
sum += inFile.nextDouble();
}
output = String.format("The total value of the items in the data file is $ %.2f", sum);
JOptionPane.showMessageDialog(null, output,
"File Totals",
JOptionPane.INFORMATION_MESSAGE);
inFile.close();
System.exit(0);
}
}
Seems to be OK when I run it. My file had 1.141<new line>2.254<newline>
and I got a dialog saying "The total value of the items in the data file is
$ 3.40".
Perhaps you should follow tsith's advice: this will show if you are using
data that's not what you were expecting. Like:while(inFile.hasNextDouble())
{
price = inFile.nextDouble();
System.out.println("Added: " + price);
sum += price;
}