简体   繁体   English

java中的文本文件如何加减数据?

[英]How to add and subtract data from text files in java?

I have a value in the text file, say 200. The value is then added or subtracted depending on the user.我在文本文件中有一个值,比如 200。然后根据用户添加或减去该值。 For instance, if the user wants to subtract 20, the value should update to 180. Then the user adds 10, the value should update to 190. When the user wants to quit, the updated value is saved in the file (190).例如,如果用户要减去 20,则该值应更新为 180。然后用户添加 10,该值应更新为 190。当用户要退出时,更新后的值将保存在文件 (190) 中。

This is what I tried:这是我尝试过的:

Double money = inputFile.nextDouble();
        
System.out.println("What do you want to change the value to?");
double change = keyboard.nextDouble();
        
delta = money + change; 

but it says there is an Exception in thread "main" java.util.InputMismatchException但它说线程“主”java.util.InputMismatchException 中存在异常

Please try the below code to get the number from your text file then add/subtract users input with it请尝试以下代码从您的文本文件中获取数字,然后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); 
  } 

} }

You could take a look at the FileWriter to save the value and the Scanner to be able to read from the file.您可以查看FileWriter以保存该值,并查看Scanner以便能够从文件中读取。

With the scanner you're able to read and integer with nextInt() .使用扫描仪,您可以阅读 integer 和nextInt() With the FileWriter you can use the method write(String) with the string being the value.使用 FileWriter,您可以使用write(String)方法,字符串为值。

I don't want to just give you the code for you.我不想只给你代码。 Remember that google is your friend and there are alot of tutorials that explain really well and there is also the Java Docs from oracle that can be very useful.请记住,谷歌是你的朋友,有很多教程解释得很好,还有来自 oracle 的 Java 文档非常有用。

If you use Scanner to read your file, you can use nextInt() to obtain the contents of the file as an int which you can add to or subtract from.如果您使用Scanner读取文件,则可以使用nextInt()int形式获取文件的内容,您可以对其进行加减。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM