开发者

Problem with my conditions in Java

good day...

i have a problem in searching my entries in my addressbook program... i already search them... but i'm having problem with showing the "Name not found!" message if the name is not yet saved in my addressbook. Can you help me figure out what's wrong with this...

public void searchEntry() {

    int notfound = 0;
    SName = JOptionPane.showInputDialog("Enter Name to find: ");
    for (int i = 0; i < counter; i++) {
        if (entry[i].getName().equals(SName)) {
            JOptionPane.showMessageDialog(null, entry[i].getInfo2());
        }else{
            notfound++;
        }

        if (notfound != 0){
           开发者_如何学Go JOptionPane.showMessageDialog(null, "Name Not Found!");
        }
    }
}

Can you help me show the "Name not found" msg... thnx in advance


move this:

if (notfound != 0){
  JOptionPane.showMessageDialog(null, "Name Not Found!");
}

outside your for loop.

I also just realized that you're probably going to have this shown up for every single one, because you're triggering even if it's not found once. Try something like this:

SName = JOptionPane.showInputDialog("Enter Name to find: ");
boolean found = false;
Object info;
for (int i = 0; i < counter; i++) {
  if (entry[i].getName().equals(SName)) {
    found = true;
    info = entry[i].getInfo2();
    break;
  }
}
if (found){
    JOptionPane.showMessageDialog(null, info);
}else{
  JOptionPane.showMessageDialog(null, "Name Not Found!");
}


public void searchEntry() {
    boolean isFind = false;
    SName = JOptionPane.showInputDialog("Enter Name to find: ");
    for (int i = 0; i < counter; i++) {
        if (SName.equals(entry[i].getName())) {
            JOptionPane.showMessageDialog(null, entry[i].getInfo2());
            isFind  = true;
            break; // TODO: I think if you find name you should leave loop.
        }
    }
if (isFind){
    JOptionPane.showMessageDialog(null, "Name Not Found!");
}

}


Your logic is quite flawed. It seems you want to iterate over some collection of people, do a name compare and when you find someone, you want a message with string X and when you don't find any, you want a message with string Y. That being said, you should probably want to put the message handling outside the loop and have a String to store the found name and use that for the conditionalizer. Here is an example:

String  nameFound = null;

for (int i = 0; i < counter; i++) {
    if (entry[i].getName().equals(SName)) {
        nameFound = entry[i].getInfo2();
        break; // Stop looking since you found the person
    }
}

if (nameFound != null){
    JOptionPane.showMessageDialog(null, nameFound);
} else {
    JOptionPane.showMessageDialog(null, "Name Not Found!");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜