[英]How to print complete list of input through a Arraylist?
Program statement: 计划声明:
To print student age,location and many phone nos. 打印学生的年龄,位置和许多电话号码。 My code is printing the name but I am having a problem in print the complete list of mobile numbers ,My code is printing only the recent number even if student enters two mobile number. 我的代码正在打印姓名,但是我在打印手机号码的完整列表时遇到问题,即使学生输入两个手机号码,我的代码也只打印最近的号码。
What mistake I am making here: 我在这里犯了什么错误:
Below is my complete program: I have created Three classes: 下面是我的完整程序:我创建了三个类:
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);
}
}
}
My current output: 我当前的输出:
1...g[232323]
1...r[2323232]
Expected result: 预期结果:
1...g[232323,1222555]
1...r[2323232.56589]
In the while
loop where you read the phone numbers, you only keep the last phone number (since you create a new ArrayList
in each iteration). 在您读取电话号码的while
循环中,您仅保留了最后一个电话号码(因为在每次迭代中都创建了一个新的ArrayList
)。
Change it to: 更改为:
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.