计划声明:
打印学生年龄,地点和许多电话号码。
我的代码正在打印名称,但我在打印完整的手机号码列表时遇到问题,即使学生输入了两个手机号码,我的代码也只打印最近的号码。
我在这里犯了什么错误:
以下是我的完整计划: 我创建了三个类:
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]
答案 0 :(得分:3)
在您阅读电话号码的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());
}