【问题标题】:how to take input from user and insert it in a arrayList如何从用户那里获取输入并将其插入到arrayList中
【发布时间】:2015-04-09 10:07:51
【问题描述】:

我有一个学生类,我的数组列表是学生类型。现在,我如何从用户那里获取输入并将其插入到我的数组列表中?

【问题讨论】:

  • First Google How to Take Input in Java ,然后将每个输入存储到对象的属性中,最后将其添加到列表中!!
  • 请告诉我们您已经尝试过什么,我们很乐意为您提供帮助。
  • 通过编写代码来做到这一点。您可以使用 Scanner 实例或 JOptionPane 框作为输入,并使用 .add 方法将信息添加到 ArrayList 中。

标签: java arraylist collections


【解决方案1】:

我想这就是你要找的东西

   ----------------------- Main Class File --------------------
   public class TestingClass {
      public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Please enter the number of students detail : ");
        int numberOfInputs = input.nextInt();

        ArrayList<Student> StudentList = new ArrayList<Student>();


        for( int i=0;  i < numberOfInputs ; i++){
            System.out.println("Please enter Name : ");
            String name = input.next();
            System.out.println("Please enter Address : ");
            String address = input.next();

            Student std = new Student(name, address);
            StudentList.add(std);
        }

        for(Student std : StudentList){
            System.out.println(std.toString());
        }
     }
    }


   -------------------- Student Java File ----------------------
     public class Student {

       public String    name    = "";
       public String    address = "";

       public Student(String name2, String address2) {

           this.name = name2;
           this.address = address2;
       }

     @Override
     public String toString() {

         return "Student [name=" + this.name + ", address=" + this.address + "]";
        }

     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    相关资源
    最近更新 更多