gpt4 book ai didi

java - 读取和写入文件无法正常工作

转载 作者:行者123 更新时间:2023-12-01 12:53:36 26 4
gpt4 key购买 nike

我今天一直在编写这段代码,快要完成了。我想要的是,代码应该像剪贴卡一样工作,记住购买的咖啡数量,并为顾客每购买 10 次就奖励一杯免费咖啡。我正在写入一个文件并从中读取,以便客户能够继续他上次留下的剪贴卡。所以对于我的问题......我已经能够正确地将我的“count”变量写入文件,并且它正确地存储它。然而,每次我再次运行该程序时,它都会从 0 开始,我不明白为什么。我需要它来保存当前计数,并在再次运行时读取计数。例如,如果顾客之前购买了 7 杯咖啡并要返回商店,则他的柜台需要从 7 开始。由于某种原因,它没有这样做。

这是我到目前为止所拥有的:

public class FelixNeww {

public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";

FelixNeww f = new FelixNeww();

System.out.println(f.readFromFile());

while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
entry = key.nextLine();
if(entry.compareTo(password) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
f.saveToFile(count);
}
if(count == 10 && count != 0){
System.out.println("YOU'VE GOT A FREE COFFE!");
count = 0;
}
if(entry.compareTo(password) != 0){
System.out.println("Wrong password! Try again.\n");
}
}



}

public void saveToFile(int count)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("C:\\Temp\\countStorage.txt"))));
bw.write(Integer.toString(count));
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(bw != null)
{
try
{
bw.close();
}
catch(IOException e) {}
}
}
}

public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch(IOException e) {}
}
}
return 0;
}


}

最佳答案

您当前将 count 变量设置为 0。您应该将其设置为文件中的值。在 while 循环之前执行此操作:

count = f.readFromFile();
while(true) {

您还应该实现一种优雅退出 while 循环的方法。例如,如果用户输入“q”,则可以执行 break; 语句来退出 while 循环。在 while 循环之后,调用 key.close(); 关闭 Scanner 对象。

关于java - 读取和写入文件无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24041576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com