2017-02-11 86 views
0

不知道如何去做这件事,但我有下面的代码片段,我的for循环遍历数组中的每个对象元素并检查if语句中的条件。如果符合if语句的条件,我想退出for循环而不继续迭代其余的数组对象。有没有一种方法可以构建我的循环来做到这一点? (假设所有的属性都被初始化)退出嵌套循环

public void remove() 
    { 
     in = new Scanner(System.in); 
     System.out.print("Please enter the destination name to be removed: "); 
     nameSearch = in.nextLine(); 
     for(i=0; i < MAX_ELEMENT; i++) 
     { 
      temp = aDestination[i].getName; 
      if(temp == nameSearch) 
      { 
       aDestination[i]=null; 
      } 
     } 
    } 

回答

0

我假设你想多次调用remove()方法。

这里是正确的修饰你:

public void remove() 
    { 
     in = new Scanner(System.in); 
     System.out.print("Please enter the destination name to be removed: "); 
     nameSearch = in.nextLine(); 
     for(i=0; i < MAX_ELEMENT; i++) 
     { 
      // we skip removed destination from previous remove() call 
      if(aDestination[i]==null) continue; 

      temp = aDestination[i].getName; 
      // you need to use equals() to compare String in Java 
      if(temp.equals(nameSearch)) 
      { 
       aDestination[i]=null; 
       break; // to exit from the loop 
      } 
     } 
    } 
+0

谢谢,真的很有帮助 – jacob

0

要做到这一点,你可以使用关键字break,什么JAVA提供。如下所示:

public void remove() { 
      in = new Scanner(System.in); 
      System.out.print("Please enter the destination name to be removed: "); 
      nameSearch = in.nextLine(); 
      for(i=0; i < MAX_ELEMENT; i++) { 
        temp = aDestination[i].getName; 
        if(temp == nameSearch) { 
         aDestination[i]=null; 
         break; 
       } 
      } 
    } 

只要条件成立就会中断当前运行循环。但是,如果你有多个嵌套循环,并且想要从某个特定循环中出来,可以使用Labeled Break。

虽然那不是你的要求,但如果你想知道这个问题你可以参考下面的教程:

http://www.java-examples.com/java-break-statement-label-example

+0

谢谢您的帮助。 – jacob

0

采用突破指令是这样的:

if(temp == nameSearch) 
{ 
    break; // immediatly quit the loop 
    aDestination[i]=null; 
}