简体   繁体   中英

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. 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).

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

Please try the below code to get the number from your text file then add/subtract users input with it

// 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.

With the scanner you're able to read and integer with nextInt() . With the FileWriter you can use the method write(String) with the string being the value.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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