gpt4 book ai didi

java - 这个程序需要多个ArrayList吗?

转载 作者:行者123 更新时间:2023-12-02 13:15:15 27 4
gpt4 key购买 nike

我必须编写一个程序来读取最喜欢的文件,例如最喜欢的动物。假设它读入一个文件,其中写着“Dog,Cat,Fox”,每行 1。然后将它们放入数组列表中。在提示用户添加或删除任何内容后,他们会被要求对它们进行排名。这就是我感到困惑的地方 - 要对 arraylist 的行进行重新排序/排名,我是否需要第二个 ArrayList 来进行排名?此外,在对他们进行排名后,他们会被要求为每一个添加评论,例如对于猫——“我对猫过敏”或类似的东西。我需要为这些评论提供第三个数组列表吗?这是一个示例输出-

‘ Collection 夹’|排名|本轮评论(加上所有之前的评论)

如果你想看看我要去哪里,现在这是我的代码 - 它并不完全有效,但你会明白它的要点

 Scanner input = new Scanner(System.in);
ArrayList <String> favoriteAnimals = new ArrayList <String>();
boolean repeat = true;
while (repeat) {

System.out.println("Enter the name of the file which contains your favorite animals ");
String fileName = input.nextLine().trim();

try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

String line;
System.out.println("Here are your favorite animals according to the file:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
favoriteAnimals.add((line));
}

System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
favoriteAnimals.add(input.next());
} else {
break;
}
for (int i = 0; i < favoriteAnimals.size(); i++) {
System.out.println(favoriteAnimals);
}

System.out.println("Remove an animal?");

if (input.next().startsWith("y")) {
System.out.println("Which animal would you like to remove");
String removeAnimal = input.nextLine();
int index = favoriteAnimal.indexOf(removeAnimal);
favoriteAnimals.remove(index);
System.out.println(favoriteAnimals);
}
else {
break;
}

ArrayList <String> ranking = new ArrayList <String>();
int size = favoriteAnimals.size();
String first = favoriteAnimals.get(0);
System.out.println("What is your ranking of " + first + " out of " + size +"?");


}



catch (IOException ex) {
System.err.println("Your file does not exist!: " + ex.getLocalizedMessage());
repeat = true;
}
}
}
}

最佳答案

很可能,您应该写一个小class Animal字段如 String name , String comment等等,然后有 ArrayList<Animal> .

关于java - 这个程序需要多个ArrayList吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43815659/

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