2015-11-17 56 views
-1
public class ForLoopDemo { 
    public static void runForLoop(int start, int stop, int increment) { 
     for (int counter = start; counter <= stop; counter = increment) { 
      System.out.println(counter); 
     } 
    } 
} 

public class ForLoopDemoRunner { 
    public static void main(String[] args) { 
     System.out.print("start 2 : stop 90 : increment 5"); 
     ForLoopDemo.runForLoop(2, 90, 5); 
    } 
} 

工作出於某種原因,這一切都運行在555(重複),當它應該運行:的Java For循環無法正常

2 7 12 17 22 27 32 37 42 47 52 57 62 67 72 77 82 87 

也是我的老師讓我們把它放在一個二級格式。

+3

你覺得'counter = increment'的確如此嗎?你不覺得它應該是'counter + =增量'嗎? – Pshemo

+1

我認爲這是錯誤的,但我不知道如何正確打印結果。我的老師給了我這個視頻,但它不起作用。 https://www.youtube.com/watch?v=rjkYAs6gAkk – ChrisManfredi

回答

0

請如下(我測試)解決您的ForLoopDemo:

public class ForLoopDemo { 
    public static void runForLoop(int start, int stop, int increment) { 
     for (int counter = start; counter <= stop; counter += increment) { 
      System.out.println(counter); 
     } 
    } 
} 

輸出:

start 2 : stop 90 : increment 52 
7 
12 
17 
22 
27 
32 
37 
42 
47 
52 
57 
62 
67 
72 
77 
82 
87 
+1

感謝您的幫助 – ChrisManfredi

+0

@ChrisManfredi謝謝! –

3

看看這個:

for(int counter = start; counter <= stop; counter = increment) 
{ 
    System.out.println(counter); 
} 

counter總是低於stop所以循環會一直持續下去。

修復此通過counter += increment

1

你的計數器是在相同的當前位置。請更新如下:

public static void runForLoop(int start, int stop, int increment) 
{ 

    for(int counter = start; counter <= stop; counter = counter + increment) 
    { 
     System.out.println(counter); 
    } 

}