gpt4 book ai didi

java - 返回 ArrayList 项而不是 boolean 值

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

在下面的代码中,我定义了一个名为 loadItems 的方法, 它应该创建类型为 Item 的数组列表文本文件的每一行。

  • Item 对象由一个包含名称的字符串和一个带有数字的 int 变量组成。
  • 文本文件的每一行都包含一个要存储在新项目中的名称,后跟=。在此之前,需要存储在新项目中的数字。总结一下,每一行看起来像:String=int .

问题在于,不是返回一个新项目并将其存储在 loadItems 中数组列表,我得到一个错误,因为它应该返回一个 boolean 值。我认为这是因为新项目是在 while 函数内创建的,该函数检查文本文件中的新行。

    ArrayList<Item> loadItems() throws FileNotFoundException {

File phaseOneFile = new File("Phase-1.txt");
Scanner readPhaseOneFile = new Scanner(phaseOneFile);

while (readPhaseOneFile.hasNextLine()){
String actualLine = readPhaseOneFile.nextLine();
String[] actualLineToItem = actualLine.split("=");

Item newItem = new Item();
newItem.itemName=actualLineToItem[0];
newItem.itemWeight= Integer.parseInt(actualLineToItem[1]);

return loadItems().add(newItem);

}

}

最佳答案

几件事。

  • 你回来得太早了
  • 您退回了错误的东西
  • 您无缘无故地使用递归

首先,您应该构建列表后立即返回,因此删除 return .

其次,循环结束后返回列表

第三,在实际ArrayList 中积累东西并返回它而不是递归。

第四,不需要返回具体类型,只返回一个List<Item> .

List<Item> loadItems() throws FileNotFoundException {

File phaseOneFile = new File("Phase-1.txt");
Scanner readPhaseOneFile = new Scanner(phaseOneFile);
List<Item> items = new ArrayList<Item>();

while (readPhaseOneFile.hasNextLine()){
String actualLine = readPhaseOneFile.nextLine();
String[] actualLineToItem = actualLine.split("=");

Item newItem = new Item();
newItem.itemName=actualLineToItem[0];
newItem.itemWeight= Integer.parseInt(actualLineToItem[1]);

items.add(newItem);

}

return items;

}

关于java - 返回 ArrayList 项而不是 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57268364/

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