簡體   English   中英

如何通過Arraylist打印輸入的完整列表?

[英]How to print complete list of input through a Arraylist?

計划聲明:
打印學生的年齡,位置和許多電話號碼。 我的代碼正在打印姓名,但是我在打印手機號碼的完整列表時遇到問題,即使學生輸入兩個手機號碼,我的代碼也只打印最近的號碼。

我在這里犯了什么錯誤:

下面是我的完整程序:我創建了三個類:

public class MyStudents {

    int age;
    String location;
    int size;
    ArrayList<String> mob;

    MyStudents(int age, String location, ArrayList<String> mob, int size) {
        this.age = age;
        this.location = location;
        this.size = size;
        this.mob = mob;
    }

    public int getAge() {
        return age;
    }

    public String getLocation() {
        return location;
    }

    public ArrayList<String> getMobileNumber() {
        return mob;
    }
}

public class AddStudentDetails {

    List<MyStudents> arrayList = new ArrayList<>();

    List<MyStudents> buildStudents() {
        System.out.println("ENTER no.OF STUDENTS");
        Scanner in = new Scanner(System.in);
        MyStudents myStudents = new MyStudents(0, null, null, 0);
        int numberOfStudents = in.nextInt();

        ArrayList<String> mob1 = new ArrayList<>();
        while (numberOfStudents > 0) {
            System.out.println("Enter How many mobile numbers You want to provide:");
            int size = in.nextInt();
            int age = in.nextInt();
            String location = in.next();

            int i = 1;
            while (size > 0) {
                mob1 = new ArrayList<>();
                System.out.println("Enter your" + i + "mobile number:");
                String num = in.next();
                mob1.add(num);

                i++;
                size--;
                System.out.println(mob1.size());
            }
            myStudents = new MyStudents(age, location, mob1, size);
            arrayList.add(myStudents);
            numberOfStudents--;
            System.out.println("num"+numberOfStudents);
        }
        return arrayList;
    }
}

public class FetchStudentDetails {

    public void fetchdetails() {
        // TODO Auto-generated method stub
        AddStudentDetails add = new AddStudentDetails();
        List<MyStudents> fetch = add.buildStudents();

        for (MyStudents ms : fetch) {
            System.out.println(ms.age+"..."+ms.location+""+ms.mob);
        }
    }
}

我當前的輸出:

1...g[232323]
1...r[2323232]

預期結果:

 1...g[232323,1222555]
  1...r[2323232.56589] 

在您讀取電話號碼的while循環中,您僅保留了最后一個電話號碼(因為在每次迭代中都創建了一個新的ArrayList )。

更改為:

mob1=new ArrayList<>();
while(size>0){
    System.out.println("Enter your"+ i +"mobile number:");
    String num=in.next();
    mob1.add(num);

    i=i+1;
    size--;
    System.out.println(mob1.size());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM