如何在java中使用For循环外的else条件
找到映像名称后,条件将被中断,并在JLable中设置名称。但当找不到映像名时,应运行else条件 其他条件写在哪里?我想在找不到图像名称时显示消息如何在java中使用For循环外的else条件,java,Java,找到映像名称后,条件将被中断,并在JLable中设置名称。但当找不到映像名时,应运行else条件 其他条件写在哪里?我想在找不到图像名称时显示消息 for( k=0;k<imageList.length;k++) { if(imageList[k].equals(name)) { lblShowName.setText("Image Code : "+imageList[k]); ImageIcon imgicon = new
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;
}
}
for(k=0;k如果没有if
语句,则不能使用else
语句。if
语句的范围在循环内,因此不能在for循环外使用else
如果设置了标签,则可以设置某种标志
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.
}
布尔标签集=false;
对于(k=0;k可以使用布尔变量,如果变量为false,则显示错误消息
您的代码可以这样修改
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
}
boolean isFound=false;
for(k=0;kfor循环结束时,tou应检查图像是否已设置:
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
}
for(k=0;kAs是@Ezio在第一个答案中提到的,如果else作用域被限制为for循环,那么它不能在循环之外,所以上述实现可以工作