简体   繁体   中英

how to use else condition outside the For Loop in java

When the image name is found then the condition will be break and set the name in JLable. But when image name not found, the else condition, should be run.

Where to write else condition? i want to show the message when image name is not found.

for( k=0;k<imageList.length;k++) {
    if(imageList[k].equals(name)) { 
        lblShowName.setText("Image Code : "+imageList[k]);
        ImageIcon imgicon = new ImageIcon(file+"\\"+imageList[k]);
        lblImage.setIcon(imgicon);
        break;
    }
}

You cannot use an else statement without an if statement. The scope of the if statement is inside the loop so you wont be able to use else outside the for loop.

You can have some kind of a flag which will be set if the label is set.

boolean labelSet = false;
for( k=0;k<imageList.length;k++) {
    if(imageList[k].equals(name)) { 
        lblShowName.setText("Image Code : "+imageList[k]);
        ImageIcon imgicon = new ImageIcon(file+"\\"+imageList[k]);
        lblImage.setIcon(imgicon);
        labelSet = true;
        break;
    }
}

if(!labelSet) {
    //show the error message here.
}

You can use a boolean variable, if variable is false then show your error message

Your code can be modified this way

boolean isFound = false;
for( k=0;k<imageList.length;k++) {
 if(imageList[k].equals(name)) {
    isFound = true; 
    lblShowName.setText("Image Code : "+imageList[k]);
    ImageIcon imgicon = new ImageIcon(file+"\\"+imageList[k]);
    lblImage.setIcon(imgicon);
    break;
  }
}

if(!isFound){
  //your error message
}

At the end of for loop tou should check whether the image has been set or not:

for( k=0;k<imageList.length;k++) {
    if(imageList[k].equals(name)) { 
        lblShowName.setText("Image Code : "+imageList[k]);
        ImageIcon imgicon = new ImageIcon(file+"\\"+imageList[k]);
        lblImage.setIcon(imgicon);
        break;
    }
}

if (lblImage.getIcon() == null) {
// do some else actions
}

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