gpt4 book ai didi

java - 文本文件写入后为空。获取索引越界

转载 作者:行者123 更新时间:2023-12-01 18:39:52 25 4
gpt4 key购买 nike

代码要求用户输入商品名称、价格和数量。我看到它创建了一个文件,但里面没有字符串?缓冲区有问题吗?提前致谢,

用户输入:输入商品名称:商品1输入商品价格 $14输入商品数量:3您想要另一件商品吗?是(y)或否(n)n

代码:

while(userInput.charAt(0)!='n'){
System.out.print("Enter item name: ");
itemName = kybd.nextLine();
PrintWriter out0 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));

System.out.print("Enter item price $");
price = kybd.nextLine();
PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));

System.out.print("Enter item quantity: ");
quantity = kybd.nextLine();
PrintWriter out2 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));


System.out.print("Do you want another item? Yes(y) or No(n)");
userInput= kybd.next();
}//end of whileLoop

编辑后仍然相同 - 文件内没有字符串:

while(userInput.charAt(0)!='n'){
PrintWriter out0 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));

System.out.print("Enter item name: ");
itemName = kybd.nextLine();
out0.println(itemName);

update2: 好的,最后是刷新 out0.flush();我的输出是:item1//nextline,price//nextline,quantity//nextLine ...我如何使其保持在同一行,以便稍后可以使用hasNext进行一些操作?

更新3:获取indexOutOfBound。文件保存成功后。我打开该文件来执行以下任务:查找每个项目的总 cost、totalCount 和总和。不知道为什么我会越界。错误指出totalCost =+ Double.parseDouble(index[1].trim());源代码:

Scanner data = new Scanner(new File("registryCopy.txt"));

while(data.hasNext()){
String line = data.nextLine();
System.out.println(line);

String[] index = line.split("\\t");
totalCost += Double.parseDouble(index[1].trim());
totalCount += Integer.parseInt(index[2].trim());

sum = totalCost/totalCount;

}

最佳答案

您不是写此信:

PrintWriter out0 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));

(或您的其他两位作家),但只是打开它准备写作。尝试写入它并刷新/关闭它。

查看this SO question/answer有关如何写入文件的更多信息。

关于java - 文本文件写入后为空。获取索引越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20388424/

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