【问题标题】:Validating string input using while loop使用 while 循环验证字符串输入
【发布时间】:2017-07-27 15:40:41
【问题描述】:

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

    }

}

【问题讨论】:

  • 你永远不会给 Y 或 N 赋值,然后在比较中使用它们。
  • 您的 YN 是空对象。没有任何东西等于 null 对象。
  • 尝试使用调试器单步调试代码。

标签: java loops while-loop


【解决方案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 警告的那样,您的条件设计错误。

【讨论】:

  • 另外!input.equalsIgnoreCase(Y) || !(input.equals(N)) 是错误的。应该是!(input.equalsIgnoreCase(Y) || input.equalsIgnoreCase(N))
  • @talex 正确。感谢朋友的提醒。
  • 如果你把它添加到你的问题中,它就变得完整了,但没用,因为无论如何都必须将问题作为离题删除,
  • 添加了新条件。
【解决方案2】:

您将输入与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条件

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 2021-05-13
      • 2016-05-27
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      相关资源
      最近更新 更多