【问题标题】:Java looped Scanner.hasNext() always evaluating to false after first evaluation is falseJava looped Scanner.hasNext() 在第一次评估为假后总是评估为假
【发布时间】:2019-09-11 02:53:31
【问题描述】:

我正在寻找一种方法来检查用户输入是否满足提示问题。例如,用户可以通过输入 y、Y、n 或 N 来回答提示“输入 Y 或 N”。如果输入满意,则该方法返回以大写形式输入的字符。否则将显示另一个提示“Invalid char”,并且扫描仪会检查下一次输入尝试。

我运行了程序,该方法正确检查了第一次输入尝试。但是,问题在于,如果第一次输入尝试错误并且显示“Invalid char”,则任何后续输入尝试都将不令人满意,即下面代码中的 sc.hasNext() 现在总是错误的。因此,程序卡在了 while 循环中。

奇怪的是,我一周前运行了这个确切的代码,它按预期工作。如果有帮助,我正在使用适用于 Android 的 Java N-IDE 应用程序。

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
   verifyInputChar("Enter Y or N", "yn");
  }

  public static char verifyInputChar(String prompt, String acceptedChars){
  Scanner sc = new Scanner(System.in);
  System.out.println(prompt);
  while(!sc.hasNext("^(?i)[" + acceptedChars.toUpperCase() + "]$")) {
     System.out.println("Invalid char.");
     sc.next();
  }
  char input = Character.toUpperCase(sc.next().charAt(0));
  System.out.println(input);
  sc.close();
  return input;    
  } 
}

【问题讨论】:

    标签: java java.util.scanner


    【解决方案1】:

    我不会使用正则表达式来执行此操作,您没有重用Pattern,因此它甚至看起来都不是优化。相反,我建议您只需阅读您的input 检查acceptedChars 中是否有匹配项

    public static char verifyInputChar(String prompt, String acceptedChars) {
        Scanner sc = new Scanner(System.in);
        System.out.println(prompt);
        String input = sc.next().toUpperCase();
        while (!acceptedChars.toUpperCase().contains(input)) {
            System.out.println("Invalid char.");
            input = sc.next().toUpperCase();
        }
        char ch = input.charAt(0);
        System.out.println(ch);
        return ch;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      相关资源
      最近更新 更多