2014-09-06 124 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