gpt4 book ai didi

java - 如何从可能存在或不存在的文件中读取字符串?

转载 作者:行者123 更新时间:2023-11-30 09:01:13 24 4
gpt4 key购买 nike

我正在编写一个程序来打开最初看起来像这样的文件:

3000.0Lamps 15.3 400Chairs 19.95 250Desks 95.0 300

where the first line is the balance of a company, and the rest of the lines contain the product name, the price, and the quantity, respectively.

However, throughout the program, we make changes to the file and save what's been done at the end using the Printwriting object. One of the things we can do during the course of the program is add new items to the inventory. However, I must be able to read in a product that has multiple names, i.e. desk chairs, for instance. As my code is written now, the file only reads in the name then moves right to the price, so if I try to read in a multi-word name, it gives me a runtime error as I'm trying to read in a string with a double. Therefore, how do I read in a line that MAY OR MAY NOT have two strings in it? And, if there are two strings, how do I write it so that it stores both of them in the same String variable? Here is my code:

    File file = new File("inventory.txt");
Scanner inputFile = new Scanner(file);

ArrayList<String> productName = new ArrayList<String>();
ArrayList<Double> productQuantity = new ArrayList<Double>();
ArrayList<Double> productPrice = new ArrayList<Double>();

double balance = inputFile.nextDouble();

while (inputFile.hasNext())
{
String product = inputFile.next();
double price = inputFile.nextDouble();
double quantity = inputFile.nextDouble();

//Takes those variables and stores each of them in ArrayList objects
productName.add(product);
productPrice.add(price);
productQuantity.add(quantity);
}

inputFile.close();

最佳答案

您可以做的一件事是在将空格存储在文件中时用连字符或其他一些字符替换空格。这样,您就可以将其作为单个单词读出,然后将字符替换为空格,从而避免更改您提供的代码。

但是如果您无法控制文件的写入方式,那么您可以尝试将 nextDouble() 函数放在 try block 中,以查看您查看的是价格还是名称的下一个单词。此处请注意,如果产品名称的第二个单词是数字,则不会按设计工作。

File file = new File("inventory.txt");
Scanner inputFile = new Scanner(file);

ArrayList<String> productName = new ArrayList<String>();
ArrayList<Double> productQuantity = new ArrayList<Double>();
ArrayList<Double> productPrice = new ArrayList<Double>();

double balance = inputFile.nextDouble();

while (inputFile.hasNext())
{
String product = inputFile.next();
try{
double price = inputFile.nextDouble();
}
catch(Exception e){
product = product+" "+inputFile.next();
double price = inputFile.nextDouble();
}
double quantity = inputFile.nextDouble();

//Takes those variables and stores each of them in ArrayList objects
productName.add(product);
productPrice.add(price);
productQuantity.add(quantity);
}

inputFile.close();

关于java - 如何从可能存在或不存在的文件中读取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26474527/

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