【问题标题】:Prompting the user for names and storing them in an ArrayList提示用户输入名称并将它们存储在 ArrayList 中
【发布时间】:2021-06-30 10:40:46
【问题描述】:

我可以提示用户输入姓名并让我的dowhilecontinue 向他们询问姓名,但我不知道如何将它们存储到ArrayList 中。我见过一些例子,但它们都要求用户输入一定数量的元素。

我只需要提示用户输入姓名,然后不断询问并提示用户输入更多姓名。然后最终打印所有名称。直到用户输入 N

import java.util.Scanner;

public class Main {
  
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        ArrayList<People> list = new ArrayList<People>();
        String a = ""; 
        do{
            System.out.println("Enter your first and last name: ");
            String name1 = scan.nextLine();

            System.out.println("Would you like to enter another name? (Y/N)");
            a = scan.nextLine();
        } 
        while(a.equalsIgnoreCase("Y"));

    }
}

【问题讨论】:

  • java !== javascript

标签: java arrays


【解决方案1】:

尝试以下解决方案,

People.java

public class People {

    private String name;
    // other variables of People

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    // other getters and setters
}

Main.java(已编辑)

public class Main {
      
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        ArrayList<People> list = new ArrayList<People>();
        String a = "";
        boolean contain = false; // declare the boolean variable for store the status of name matching
        
    do {
        System.out.println("Enter your first and last name: ");
        String name1 = scan.nextLine();
        People people = new People(); // initialize a new people object
        people.setName(name1); // set the name to above people
        list.add(people); // add people object into ArrayList of People

        System.out.println("Would you like to enter another name? (Y/N)");
        a = scan.nextLine();
    } while(a.equalsIgnoreCase("Y"));
    
    
    System.out.println("Pleaes enter the name for search");
    String name = scan.nextLine();
    
    for (int i = 0; i < list.size(); i++) {
        if(list.get(i).getName().equals(name)){
            System.out.println(name+" is in position "+i);
            contain = true; // set contain variable to true when match the given name with people in ArrayList
            break; // if match the name, break the loop
        }
    }
    if(!contain){ // if not contain the people with given name in ArrayList, execute following message
        System.out.println("this people not contain in list");
    }

    }
}

有关如何在ArrayList 中搜索自定义对象的更多方法,请参考this question

【讨论】:

  • 这对我很有帮助,谢谢,如果我想在这个 ArrayList 中搜索,我该如何开始?可以说,我输入了 Apples Oranges Tomatoes Cucumber 之类的名称,如果我想搜索 Cucumber,我希望它回复“Cucumber is in position 4”
  • @BrandonZywoo 请参考上面修改后的答案
猜你喜欢
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
  • 1970-01-01
相关资源
最近更新 更多