如何从用户获取输入并将其插入arrayList

时间:2015-04-09 10:07:52

标签: java arraylist collections

我有一个学生班,我的arraylist是学生类型。现在,我如何从用户那里获取输入并将其插入我的arraylist?

1 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西

   ----------------------- 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 + "]";
        }

     }