2014-03-29 74 views
0

我在这个程序中遇到问题,当我输入正确的值时,它给了我正确的输出,但它也要求我再次输入我的名字。它正在工作,当我输入一个不正确的值3次它将终止程序,尽管它不打印出错误信息。我不知道如何改变它,以便它只会输出您验证过的电梯。输入正确的值后程序不会退出循环

import java.util.Scanner; 


public class Username 
{ 


public static void main (String[]args) 



{ 
    Scanner kb = new Scanner (System.in); 
    // array containing usernames 
    String [] name = {"barry", "matty", "olly","joey"}; // elements in array 
    boolean x; 
       x = false; 
    int j = 0; 
      while (j < 3) 
      { 


       System.out.println("Enter your name"); 
       String name1 = kb.nextLine(); 
       boolean b = true; 

       for (int i = 0; i < name.length; i++) { 

        if (name[i].equals(name1)) 
        { 

         System.out.println("you are verified you may use the lift"); 
         x = true; 
         break;// to stop loop checking names 

        } 



       } 
       if (x = false) 
       { 
        System.out.println("wrong"); 
       } 

       j++; 



      } 

      if(x = false) 
      { 
       System.out.println("Wrong password entered three times. goodbye."); 

      } 

}} 

回答

3

在你if (x = false)你第一次分配falsex,然后在条件检查。换句话说,你的代码是类似于

x = false; 
if (x) {//... 

你可能想写

if (x == false) // == is used for comparisons, `=` is used for assigning 

但不使用编码的这种风格。相反,你可以使用Yoda conditions

if (false == x)// Because you can't assign new value to constant you will not 
       // make mistake `if (false = x)` <- this would not compile 

甚至更​​好

if (!x)// it is the same as `if (negate(x))` which when `x` would be false would 
     // mean `if (negate(false))` which will be evaluated to `if (true)` 
     // BTW there is no `negate` method in Java, but you get the idea 

形式if(x)等于if (x == true)因为

true == true < ==>true
false == true < ==>false

这意味着

X == true < ==>X(其中X只能真或假)。

同样if (!x)表示if(x == false)