提问人:metal 提问时间:6/10/2022 更新时间:6/10/2022 访问量:79
如何改进从文本文件中的收据总额计算总和的程序?
How can I improve a program that calculates a sum from receipt totals from a text file?
问:
到目前为止,我在下面有这个程序:
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;
}
}
}
}
在文本文件中,我有一个数字(例如:“0.00”),程序应该获取该数字,然后使用它进行计算。receipt.txt
- 有一个错误指出:
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)
我该如何解决这个问题?
- 有没有办法使它从文本文件中删除总和并将其添加到用户的输入中,然后在文件中再次打印出来以再次使用?或者有更好的方法来重复计算总和?
FileWriter
答: 暂无答案
评论
InputMismatchException
scan.nextDouble();
receipt.txt