2014-09-06 208 views
-1

我的代碼有沒有語法錯誤,但是當我啓動程序,我應該得到我需要幫助(邏輯)

class verschlüsselung { 

    private static void search(int b, int a) { 

     b = 1; 
     Random r = new Random(); 
     a = r.nextInt(9); 
     System.out.println(a); 

     while (a != b) { 
      for (b = 0; b == 9; b++) { 
       if (b == a) { 
        System.out.println("found the number " + b); 
       } 
      } 
     } 
    } 

    public static void main(String args[]) { 
     search(0, 0); 
    } 
} 

我感謝每一個解釋,我沒有在控制檯中看到該消息。

+2

使用類名稱變音氣餒。 – MrTux 2014-09-06 16:38:40

+0

「我沒有在控制檯中得到消息,因爲我應該得到」你的代碼假設要做什麼?你期望輸出什麼? – Pshemo 2014-09-06 16:38:44

+0

你的循環只在'a!= b'時執行,並且在你檢查總是假的if(b == a)'時 – karthikr 2014-09-06 16:39:05

回答

0

你的循環中的條件應該是b < 9,否則你永遠不會進入它的身體。但是,做你想做的最好的辦法是:

b = 0; 
while (a != b) b++; 
System.out.println("found the number " + b); 
0

兩個問題:

  1. 像提到的其他人:你應該b < 9切換b == 9(這樣的循環體將執行而b小於9)
  2. 在「找到號碼」打印後,您應該添加一條return;聲明 - 否則您可能會陷入無限(while)循環。

while (a != b) { 
    for (b = 0; b < 9; b++) { // b < 9 
     if (b == a) { 
      System.out.println("found the number " + b); 
      return; // second change 
     } 
    } 
} 

一些更多的評論:

  • 沒有意義,通過ab作爲參數傳遞給search(),因爲你做的第一件事是重新分配它們。
  • b只用在for循環,無需在較廣範圍聲明它
  • while環是不必要

下面的代碼將這樣做:

public static void main(String[] args) { 
    search(); 
} 

private static void search() {  
    Random r = new Random(); 
    int a = r.nextInt(9); 

    for (int b = 0; b < 9; b++) { 
     if (b == a) { 
      System.out.println("found the number " + b); 
      return; 
     } 
    }  
} 

值得一提的是,現在我們沒有包裝while循環,即使我們將刪除return語句,代碼仍然可以工作!

0

首先,你可以這樣做不妥for循環,

for(b=0;b == 9; b++) 

b==9是循環必須滿足的條件。顯然,這種情況永遠不會遇到,因爲b = 0在第一步。

所以,

for (b = 0; b < 9; b++) 

爲好。

一旦找到a==b,您必須打破while循環。

while (a != b) { 
     for (b = 0; b < 9; b++) { 
      if (b == a) { 
       System.out.println("found the number " + b); 
       break; 
      } 
     } 
    } 

實際上,while循環是沒用的,流動是不夠的,

for(b = 0; b < 9; b++) 
     { 
      if (b == a) { 
       System.out.println("found the number " + b); 
       break; 
      } 
     } 
+0

非常感謝你,那真的有幫助 – Amir009 2014-09-06 18:03:26