I have to write a program that will read the names and balances from text file "balances.txt" and organize into a report that will then sum up the balances into a total. This is what the file contains:
JAKIE JOHNSON,2051.59 SAMUEL PAUL SMITH,10842.23 ELISE ELLISON,720.54 I had originally written the code which gave me exactly what I wanted, but was told not use loops, arrays, or parseDouble. I've now tried the following, but I keep getting an error every time I used nextDouble. The code:
import java.io.File; import java.text.NumberFormat; import java.text.DecimalFormat; import java.io.FileInputStream ; import java.io.FileNotFoundException ; import java.io.IOException ; import java.util.Scanner ; public class BankFile { public static void main(String[] args) throws IOException { Scanner fileIn = null; try { String filename = "balances.txt" ; File newFile = new File(filename); Scanner in = new Scanner(newFile); in.useDelimiter(","); String name = in.next(); System.out.println(name); // trying to see if first name will display double money = in.nextDouble(); System.out.println(money); // trying to see if first double will display } catch (FileNotFoundException e) { System.out.println("File not found."); System.exit(0); } } } This is the output and exception stacktrace:
JAKIE JOHNSON Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextDouble(Scanner.java:2413) at Lab2.main(BankFile.java:52) `
next,next, thennextDoubleto advance the Scanner and receive the correct input.useDelimiterwill return a new Scanner Object to use