Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用while循环验证字符串输入_Java_Loops_While Loop - Fatal编程技术网

Java 使用while循环验证字符串输入

Java 使用while循环验证字符串输入,java,loops,while-loop,Java,Loops,While Loop,我对这个简单的代码感到非常困难。始终忽略我的while条件,并执行print语句。请帮忙 package Checkpoints; import java.util.Scanner; public class Check05 { public static void main (String[]args){ Scanner keyboard = new Scanner(System.in); /** * Write an inpu

我对这个简单的代码感到非常困难。始终忽略我的while条件,并执行print语句。请帮忙

package Checkpoints;
import java.util.Scanner;


public class Check05 {
    public static void main (String[]args){

        Scanner keyboard = new Scanner(System.in);

        /**
         * Write an input validation that asks the user to enter 'Y', 'y', 'N', or 'n'.
         */


        String input, Y = null, N = null;

        System.out.println("Please enter the letter 'Y' or 'N'.");
        input = keyboard.nextLine();


        while (!input.equalsIgnoreCase(Y) || !(input.equals(N)))
                //|| input !=y || input !=N ||input !=n)

            {
            System.out.println("This isn't a valid entry. Please enter the letters Y or N" );
            input = keyboard.nextLine();
            }

    }

}
改变这一点

String input, Y = null, N = null;
对此,

String input, Y = "Y", N = "N";
while (!(input.equalsIgnoreCase(Y) || input.equalsIgnoreCase(N)))
因此,您可以将用户输入字符串与“Y”和“N”字符串进行比较

而这个,

while (!input.equalsIgnoreCase(Y) || !(input.equals(N)))
对此,

String input, Y = "Y", N = "N";
while (!(input.equalsIgnoreCase(Y) || input.equalsIgnoreCase(N)))

正如@talex警告的那样,因为您的条件设计是错误的。

您正在将输入与
null
进行比较,因为您忘记定义字符串
Y
N
的值

您可以在常量中定义答案值,如下所示:

public static final String YES = "y";
public static final String NO  = "n";

public static void main (String[] args) {
    Scanner keyboard;
    String  input;

    keyboard = new Scanner(System.in);

    System.out.println("Please enter the letter 'Y' or 'N'.");
    input = keyboard.nextLine();

    while (!(input.equalsIgnoreCase(YES) || input.equalsIgnoreCase(NO))) {
        System.out.println("This isn't a valid entry. Please enter the letters Y or N" );
        input = keyboard.nextLine();
    }
}

编辑:按照talex的建议更正了while条件

在“while”循环之前添加此额外条件以避免此问题

    if(Y!= null && !Y.isEmpty()) 
    if(N!= null && !N.isEmpty())

您从不将值赋给Y或N,然后在比较中使用它们。您的
Y
N
是空对象。没有任何对象等于
null
对象。请尝试使用调试器单步执行代码。另外
!input.equalsIgnoreCase(Y)| |!(input.equals(N))
错误。应该是
!(input.equalsIgnoreCase(Y)| | input.equalsIgnoreCase(N))
@talex Correct。谢谢你的提示。如果你把它添加到你的问题中,它会变得完整,但没用,因为问题必须作为离题删除,所以添加了新的条件。