gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:06:02 25 4
gpt4 key购买 nike

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

}

}}

最佳答案

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 <==> true
假==真 <==>

这意味着

X == true <==> X(其中 X 只能为 true 或 false)。

类似地,if (!x) 表示 if(x == false)

关于java - 输入正确的值后程序不会退出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com