我想打印是否找到 rollno
,但它仅在找到 rollno
时打印,我应该如何存在循环并获取正确的 boolean 值来打印我的值找到但未找到值。有人可以告诉我我在这里做错了什么吗?现在它只在找到值时打印,而没有;如果数组列表中不存在值,则存在。
public class StudentDB{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Creating user defined class objects
Student s1=new Student(1,"AAA",13);
Student s2=new Student(2,"BBB",14);
Student s3=new Student(3,"CCC",15);
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
/* while(itr.hasNext()){
Student st=(Student)itr.next();
if(st.rollno == 2){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
else{
continue;
}
} */
//Scanner scan = new Scanner(System.in);
System.out.println("ENter your id: ");
int id = scan.nextInt();
boolean result = false;
while(!result) {
while(itr.hasNext()) {
Student st=(Student)itr.next();
if(st.rollno == id){
result = true;
break;
}
else{
result = false;
}
}
}
if(result == true){
System.out.println("Roll no found!");
}else{
System.out.println("Roll no not found!");
}
}
}
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
最佳答案
如果未找到该值,它将进入无限循环,这就是不打印该值的原因。不需要外部 while 循环。
关于java - 我应该如何正确退出这个 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62479162/