简体   繁体   English

我应该如何正确退出这个while循环

[英]How should I exit this while loop correctly

I want to print if rollno found or not, but it only prints when rollno found, how should I exist the loops and get the correct boolean to print my Value found and value not found.我想打印是否找到rollno ,但它只在找到rollno时打印,我应该如何存在循环并获得正确的 boolean 来打印我找到的值和未找到的值。 Can someone tell me what I am doing wrong here?有人可以告诉我我在这里做错了什么吗? Right now it only prints when value found and doesn't;现在它只在找到值时打印而不是; exist if value not present in the arraylist.如果 arraylist 中不存在值,则存在。

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;  
    }  
}

It goes into an infinite loop if the value is not found, that is why value does'nt get printed.如果找不到该值,它将进入无限循环,这就是为什么不打印值的原因。 There's no need of outer while loop.不需要外部while循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM