【问题标题】:Program wont exit loop after correct value is entered输入正确的值后程序不会退出循环
【发布时间】:2014-05-09 06:10:45
【问题描述】:

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

            }

}}

【问题讨论】:

    标签: java loops while-loop boolean


    【解决方案1】:

    在您的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
    false == true false

    意思是

    X == true X(其中X 只能为真或假)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2014-05-09
      • 2016-05-08
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 2018-12-04
      相关资源
      最近更新 更多