[英]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.