2012-01-27 39 views
-1

我是一個初學者與Java和我下面的Thenewboston在YouTube上的教程。我想要更高級一點(在我看來......但不是真的)。所以繼承了代碼。我想讓它重複到開頭,這樣我就可以輸入另一個數字而無需重新啓動程序。我相信我必須使用返回命令,但我不確定在哪裏以及如何。謝謝!如何重複/循環/返回到一個類

import java.util.Scanner; 

class apples { 

    public static void main(String args[]) { 

     Scanner alex = new Scanner(System.in); 
     Double test; 
     test = alex.nextDouble(); 

     if (test == 9) { 
      System.out.println("eat"); 
     } else { 
      System.out.println("do not eat"); 
     } 
    } 
} 

回答

1
import java.util.Scanner; 

class apples{ 

    public static void main(String args[]){ 

     Scanner alex = new Scanner(System.in); 
     Double test; 
     while(true) { 
      test = alex.nextDouble(); 
      if (test == 9){ 
       System.out.println("eat"); 
      }else{ 
       System.out.println("do not eat"); 
      } 
     } 
    } 
} 
+0

謝謝。 while(true)語句的含義是什麼? – user1174394 2012-01-27 21:27:29

+0

這意味着「永遠重複」; while(條件){語句}將執行「語句」,直到「條件」變爲假 – 2012-01-27 21:47:17

+0

true始終爲真,所以你的程序將繼續輸入,直到你殺了它:) – 2012-01-27 21:53:49

1

像在C或C++中,你可以使用while語句,執行後阿斯金是用戶想要去退出或不

while (answer){ 
    // ...code... 
} 

也可以使用do..while

do{ 
    // ...code... 
}while(condition) 
+0

你能更詳細一點嗎?就像我之前說的那樣,我是初學者。我沒有使用c或C++的經驗。我應該在哪裏放置代碼和條件? – user1174394 2012-01-27 21:19:43

0

包裝你的代碼周圍while迴路,並使用break出來循環的,如果你的條件爲真。

while((alex.hasNext())) 
    { 
    test = alex.nextDouble(); 

    if (test == 9){ 
     System.out.println("eat"); 
     break; 

}else{ 
     System.out.println("do not eat"); 


} 
    } 
0

事情是這樣的:

Double test; 
Scanner alex = new Scanner(System.in); 
    while (alex.hasNextDouble()) { 
    test = alex.nextDouble(); 
     if (test == 9){ 
       System.out.println("eat"); 
       continue; 

      }else{ 
       System.out.println("do not eat"); 
        break; 

    } 

    } 

注:假設所有的投入都是雙重的,否則這個計劃可能會失敗。

這是不太完美的例子,因爲即使你不說,繼續while循環迭代。這可能是休息的好例子。