输入正确的值后,程序不会退出循环

时间:2014-03-29 19:07:38

标签: java loops while-loop boolean

我在这个程序中遇到问题,当我输入正确的值时,它会给我正确的输出,但它也要求我再次输入我的名字。当我输入不正确的值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.");

            }

}}

1 个答案:

答案 0 :(得分:3)

在您的if (x = false)中,您首先将false分配给x,然后在条件中进行检查。换句话说,您的代码类似于

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&lt; ==&gt; true
false == true&lt; ==&gt; false

表示

X == true&lt; ==&gt; X(其中X只能是真或假)。

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