gpt4 book ai didi

Java-根据文本文件中的当前日期生成已经过期的产品列表

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

我正在为我的大学学期项目(市场经理)在 Netbeans 中制作 GUI 应用程序。我们可以将任何产品添加到应用程序并将数据存储为 .txt 文件,文件名基于产品代码。1234.txt 中的示例数据:

Product code : 1234
Name : Noodle
Price : $1000
Description : Instant noodle is not good for healthy
Expiry data : 12-01-2050

我的问题是,如果已经添加了更多 .txt 文件并读取文件中的日期,并根据当前日期将过期产品列表显示为 jtextArea 作为文件名,以及用于删除所有过期文件的按钮,如何读取所有文件。

private void okBtnActionPerformed(java.awt.event.ActionEvent evt) {                                      
String code = txtCode.getText();
String name = txtName.getText();
String price = txtPrice.getText();
String expiry = txtExpiry.getText();
String quantity = txtQuantity.getText();
String description = txtDescription.getText();
int quant = Integer.parseInt(quantity);

try {
for (int i = 0; i < quant; i++) {
File file = new File("Product/"+code+i+".txt");
if (!file.exists()) {
file.createNewFile();
String content = "Code: " + code + i + "\r\nName: " + name + "\r\nPrice: RM." + price + "\r\nDescription: " + description + "\r\nExpiry Date: " + expiry;
FileWriter data = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(data);
bw.write(content);
bw.close();

JOptionPane.showMessageDialog(this, "Product Added");

txtCode.setText("");
txtName.setText("");
txtPrice.setText("");
txtExpiry.setText("");
txtQuantity.setText("");
txtDescription.setText("");
} else {
JOptionPane.showMessageDialog(this, "The Product Code Already Added");
break;
}
}

} catch (IOException e) {

}

}

此代码用于添加产品

最佳答案

您首先要分离职责。您首先创建一个代表产品的。在当前的方法中,您尝试通过一组以某种方式属于在一起的变量来“建模”产品。

相反,创建一个具有相应字段的类;例如,一个很好的 equals 方法。

然后创建一个方法,该方法采用表示文件名的字符串。该方法打开文件;读取文本数据并从中创建一个 Product 对象。我们称之为readSingleProduct() .

下一步:创建一个方法,该方法采用表示目录的字符串作为示例。该方法检查该目录中的所有文本文件并调用 readSingleProduct()为了创建 Product 对象;最后,该方法将返回一些 List<Product> .

最后,您构建接收此类 Product 对象列表的 UI 代码,并将其用作实际 UI 组件的模型。

还有一个提示:你永远不会使用 catch block 。您至少应该在那里打印异常; 忽略错误始终是一个非常糟糕的主意!

希望这能让你继续前进!

关于Java-根据文本文件中的当前日期生成已经过期的产品列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40810691/

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