2014-03-29 75 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)