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