我正在尝试编写一个程序,允许用户将字符串值输入到包含arrayLists的多个方法中。我有2个问题:面向对象与线性编程
- 我的代码似乎是线性的(我想确保我正在使用面向对象的编程原则)。
- 我很难编写while循环来将用户输入的值添加到arrayList中。由于我不知道将会输入多少个值,我认为这将是一个合适的方法。
这是我到目前为止,您的意见受到重视和赞赏:
import java.util.ArrayList;
import java.util.Scanner;
public class Animals {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
System.out.println(" Here are some animal types! ");
ArrayList<String> animalTypes = new ArrayList<String>();
animalTypes.add("Vertebrae");
animalTypes.add("Reptile");
animalTypes.add("Insect");
animalTypes.add("Amphibian");
System.out.println(" Enter new animal type");
System.out.println(" Here is your animal types list! ");
// This for loop is inadequate, I need a while loop as I don't know the exact number of entries from the user//
for (int index = 0; index < animalTypes.size(); index++) {
System.out.println(animalTypes.get(index));
}
某些逻辑像'while while true,type quit to end'用户输入可以通过Scanner.nextLine获得 –
使代码容易阅读时,使用过程代码没有任何问题。面向对象的解决方案只适用于面向对象的问题。 – 4castle
除非你想有重复的动物类型,那么我可能会建议你使用Set而不是ArrayList –