[英]How to add and subtract data from text files in java?
我在文本文件中有一个值,比如 200。然后根据用户添加或减去该值。 例如,如果用户要减去 20,则该值应更新为 180。然后用户添加 10,该值应更新为 190。当用户要退出时,更新后的值将保存在文件 (190) 中。
这是我尝试过的:
Double money = inputFile.nextDouble();
System.out.println("What do you want to change the value to?");
double change = keyboard.nextDouble();
delta = money + change;
但它说线程“主”java.util.InputMismatchException 中存在异常
请尝试以下代码从您的文本文件中获取数字,然后add/subtract
用户输入
// Java Program to illustrate reading from FileReader
// using BufferedReader
import java.io.*;
public class ReadFromFile2
{
public static void main(String[] args)throws Exception
{
// We need to provide file path as the parameter:
// double backquote is to avoid compiler interpret words
// like \test as \t (ie. as a escape sequence)
File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
您可以查看FileWriter
以保存该值,并查看Scanner
以便能够从文件中读取。
使用扫描仪,您可以阅读 integer 和nextInt()
。 使用 FileWriter,您可以使用write(String)
方法,字符串为值。
我不想只给你代码。 请记住,谷歌是你的朋友,有很多教程解释得很好,还有来自 oracle 的 Java 文档非常有用。
如果您使用Scanner
读取文件,则可以使用nextInt()
以int
形式获取文件的内容,您可以对其进行加减。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.