gpt4 book ai didi

java - 通过扫描输入文件创建对象?

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

我正在编写一个简单的程序来跟踪库存。我有一个名为“inventory-txt”的输入文件,需要扫描它并创建一个对象。该文件如下所示:

(商品、数量、价格)

笔1000 2

记事本1050 5

画笔 500 3

剪刀398 4

橡皮擦199 2

纸张重量 50 3

小号订书机 100 5

订书机-大号 50 8

标记 1000 2

这是我到目前为止得到的:

public class Item {
private String name;
private int quantity;
private double pricePerUnit;

// Constructor for class Item
Item(String name, int quantity, double pricePerUnit){
this.name = name;
this.quantity = quantity;
this.pricePerUnit = pricePerUnit;
}

// Setter method for name
public void setName(String name){
this.name = name;
}
// Getter method for name
public String getName(){
return name;
}

// Setter method for quantity
public void setQuantity(int quantity){
this.quantity = quantity;
}
// Getter method for quantity
public double getQuantity(){
return quantity;
}

// Setter method for price per unit
public void setPricePerUnit(double pricePerUnit){
this.pricePerUnit = pricePerUnit;
}
// Getter method for price per unit
public double getPricePerUnit(){
return pricePerUnit;
}

}

 public static void main(String[] args) {
// To re-factor the Inventory management program
// Task 2.a.i.
File inputFile;
Scanner Input = null;
try{
inputFile = new File("Assignment13-inventory.txt");
Input = new Scanner(inputFile);
while(Input.hasNext()){
String name = Input.next();
int quantity = Input.nextInt();
double pricePerUnit = Input.nextDouble();
System.out.println(name);
System.out.println(quantity);
System.out.println(pricePerUnit);


}


} catch(FileNotFoundException e){
System.out.println("File does not exist");
}

Input.close();

// Task 2.a.ii.

Item item1 = new Item();
item1.setName(name);
System.out.println(item1.getName());
item1.setPrice(price);
item1.setPricePerUnit(pricePerUnit);

文件已成功扫描,但我在创建每个对象时遇到困难。每个元素都应该有自己的名称、数量和价格。请帮我弄清楚如何创建这些对象!

最佳答案

创建一个List来保存您的对象,然后在读取输入后调用构造函数。

public static void main(String[] args) {
List<Item> myItems = new ArrayList<Item>();
// .... Other code.
String name = Input.next();
int quantity = Input.nextInt();
double pricePerUnit = Input.nextDouble();
myItems.add(new Item(name, quantity, pricePerUnit));
// ... Other code
}

关于java - 通过扫描输入文件创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23588794/

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