简体   繁体   中英

if statement for arraylist when using methods

The assignment I'm working on creates a menu that will search for an item or delete an item in an arraylist depending on a number that is assigned to it. I originally used a for-loop that looked like this:

                  for (Student S : list) 
                  { 
                  if (S.getsNumber() == findStudent) 
                  JOptionPane.showMessageDialog(null, S.toString()); 
                  }

but I need it to return a string like "student does not exist" when there isn't a student that matches the number entered. The problem I'm getting is it will print that statement over and over for each item in the list.. so I'm trying to create an if-statement instead of a for-loop.

I just can't figure out the code for it since the number for each student isn't in the arraylist, it's given through a method.. so if I used anything like list.contains(), it would be false.

can someone point me in the right direction?

btw, I'm definitely not asking anyone to write the code for me! just need a little help. Let me know if you need me to put up more of what I have so far.

One heuristic would be to initialize Student to some null value and then after the loop if the Student is still null create and throw an instance of a StudentNotFoundException.

If you do not want it to print multiple times do not put the print inside the loop. Pick what you want to print exit the loop then print, or tighten your logic with a Boolean that prevents the printer from running unless you have chosen what to print and then reset the Boolean to false after printing.

I am not quite sure if this is what you were asking for but this will give you the equivalent of a student not found by catching that exception.

Set a boolean inside the if statement, then check it after the for loop:

boolean found = false;
for (Student S : list) 
{ 
   if (S.getsNumber() == findStudent) {
      JOptionPane.showMessageDialog(null, S.toString()); 
      found = true;
   }
}
   if(!found) JOptionPane.showMessageDialog(null, "Student does not exist");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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