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

问题描述 投票:0回答:3

这个简单的代码让我非常艰难。我的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();
            }

    }

}
java loops while-loop
3个回答
1
投票

改变这个;

String input, Y = null, N = null;

对此;

String input, Y = "Y", N = "N";

这样您就可以将用户输入字符串与“Y”和“N”字符串进行比较。

还有这个;

while (!input.equalsIgnoreCase(Y) || !(input.equals(N)))

对此;

while (!(input.equalsIgnoreCase(Y) || input.equalsIgnoreCase(N)))

正如@talex警告的那样,你的病情设计是错误的。


0
投票

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

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

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条件


0
投票

在“while”循环之前添加此额外条件以避免这种情况

    if(Y!= null && !Y.isEmpty()) 
    if(N!= null && !N.isEmpty())
© www.soinside.com 2019 - 2024. All rights reserved.