sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-12-01 23:06:02 26 4
mua khóa gpt4 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.");

}

}}

1 Câu trả lời

hiện hữu if (x = false) 中,您首先将 SAI 分配给 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) bình đẳng if (x == true) bởi vì

true == true <==> ĐÚNG VẬY
假==真 <==>

这意味着

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

类似地,if (!x) thể hiện if(x == false).

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

26 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com