【问题标题】:Alternate method to .hasNextInt? [duplicate].hasNextInt 的替代方法? [复制]
【发布时间】:2015-12-08 20:14:32
【问题描述】:

我是 java 新手,我想知道是否可以使用其他方法代替 has.nextInt(),因为这种方法会弄乱我的扫描仪。例如

do {
    System.out.println("Please enter your full name: ");
    memberName = input.nextLine();
    if (input.hasNextInt()) {
        System.out.println("Your name cannot contain a number");
        input.next();
    } else {
        successful = true;
    }
} while (successful == false);

控制台

Create new member
Please enter your full name: 
jack 
jack

我必须输入我的名字两次才能继续 我知道有这样的问题,但我对任何解决方案都没有运气。谢谢

编辑

我正在尝试确保输入根本不包含任何数字,如果包含则

System.out.print("Your name cannot contain any numbers");

发生

【问题讨论】:

  • 你希望input.hasNextInt()做什么?
  • 你能提供一些你想接受的名字的例子吗?喜欢你要接受foo123吗?或者如果有人有两个名字,比如Jack Adam Smith
  • 我只想接受像乔博客,乔恩史蒂文斯这样的信件。我不想接受任何数字或 foo123 @Pshemo
  • 也许这篇 SO 帖子会回答你的问题:Check if String contains only letters

标签: java java.util.scanner


【解决方案1】:

if(input.hasNextInt()){ 的用法在这里是错误的。因为您想在之前输入的字符串中查找数字,即memberName

您可以为此使用正则表达式:

Pattern digitPattern = Pattern.compile("\\d+");       

然后您可以使用它来验证任何字符串:

System.out.println(digitPattern.matcher("Marcinek 234").matches());

【讨论】:

  • 你能举个例子吗?
  • 我想我已经做到了。
【解决方案2】:
do {
    System.out.println("Please enter your full name: ");
    memberName = input.nextLine();
    if (memberName.contains("1234567890")) {
        System.out.println("Your name cannot contain a number");
    } else {
        successful = true;
    }
    input.next();
} while (successful == false);

您在 if 语句中使用输入进行检查,但您将 memberName 分配给整行。

【讨论】:

    【解决方案3】:

    尝试创建自己的方法来测试传递的名称是否有效。例如,它可以看起来像这样:

    private static boolean isValidName(String name){
        return name.matches("[a-z]+(\\s[a-z]+)*");//can be optimized with precompiled Pattern
    }
    

    现在您的代码如下所示:

    System.out.println("Please enter your full name: ");
    do {
        memberName = input.nextLine();
        successful = isValidName(memberName);
        if (!successful) {
            System.out.println("Your name is not valid. Valid name can contain only letters and spaces. No digits are allowed.");
            System.out.println("Please try again: ");
        } 
    } while (!successful);
    System.out.println("welcome: "+memberName);
    

    【讨论】:

      【解决方案4】:

      如果您只想从用户输入中读取行,您可以使用:

      hasNextLine()
      

      或者你可以使用:

      hasNext()
      

      并尝试改变这一点:

       while (successful == false);
      

      有了这个:

        while (successful); 
      

      【讨论】:

        【解决方案5】:

        您可以使用:enteredName.contains("1") 检查数字。 例如:

        boolean containsNumbers = false;
        for(int i = 0; i<9; i++){
        if (name.contains(""+i)) containsNumbers = true; 
        }
        

        【讨论】:

          猜你喜欢
          • 2023-03-12
          • 2016-04-06
          • 1970-01-01
          • 2019-09-11
          • 1970-01-01
          • 1970-01-01
          • 2011-08-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多