I have this program below so far:
import javax.swing.JOptionPane;
import java.io.*;
import java.util.Scanner;
import java.text.DecimalFormat;
class Receipts
{
public static void main(String[] args) throws IOException
{
DecimalFormat format = new DecimalFormat("0.00");
File file = new File("receipt.txt");
PrintWriter exit = new PrintWriter(
new BufferedWriter(
new FileWriter(file, true)));
Scanner scan = new Scanner(file);
int choice = JOptionPane.showOptionDialog(null, "Hello. What would you like to do today?", "Receipts", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[]{"See my total", "Add a receipt"}, "default");
switch(choice)
{
case 0: // see my total
{
double total = scan.nextDouble();
String StrTotal = format.format(total);
JOptionPane.showMessageDialog(null, "Your total so far is $" + StrTotal + ".");
}
case 1: // add a receipt
{
double receipt = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount."));
double addTotal = scan.nextDouble();
exit.print(format.format(receipt + addTotal));
exit.close();
JOptionPane.showMessageDialog(null, "The amount has been added.");
}
default:
{
JOptionPane.showMessageDialog(null, "Please input your selection.");
exit.close();
break;
}
}
}
}
In the text file receipt.txt, I have a single number (like: "0.00") that the program is supposed to fetch then use it for calculations.
- There's an error stating:
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 Receipts.main(Receipts.java:26)
How can I fix this?
- Is there a way to make it so that the
FileWriterremoves the sum from the text file and adds it to the user's input, then prints it again in the file to use again? Or any better way to calculate a sum repetively?