防止用户在Java扫描仪中输入数字? [英] Prevent the user entering numbers in java Scanner?

查看:57
本文介绍了防止用户在Java扫描仪中输入数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阻止用户使用扫描仪类别输入数字时遇到了一些麻烦.这就是我所拥有的:

I am having some trouble preventing the user from entering numbers with the scanner class. This is what I have:

package palindrome;

import java.util.Scanner;

public class Palindrome {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String word;
        String inverse = "";

        System.out.println("Write a sentence or word: ");

        while (!input.hasNext("[A-Za-z]+")) {
        System.out.println("Not valid! Try again: ");
        input.nextLine();
    }
        word = input.nextLine();

        word = word.replaceAll("\\s+","");
        word = word.toLowerCase();

        int length = word.length();
        length = length - 1;

        for (int i = length; i >= 0; i--) {
            inverse = inverse + word.charAt(i);
        }

        if (word.equals(inverse)) {
            System.out.println("Is a palindrome.");
        } else {
            System.out.println("Is not a palindrome.");
        }

    }
}

基本上,当我输入单词或句子时,我希望它检查输入中是否有任何数字,如果有,那么您需要输入另一个,直到没有.这是输出示例:

Basically when I enter a word or sentence I want it to check if it has any numbers anywhere in the input, if it has then you need to enter another one until it doesn't. Here is an example of output:

  • 写一个句子或单词:

  • Write a sentence or word:

-> 11

无效!再试一次:

-> 1个测试

无效!再试一次:

->测试1

不是回文.

如您所见,它在大多数情况下都适用,但是当我输入单词FIRST,然后输入一个空格和一个数字时,它会在没有数字的情况下进行评估.我假设发生这种情况,因为在while循环中仅检查input.hasNext,但应该将其输入.hasNextLine我相信要检查整个字符串.但是,如果这样做,我将没有任何论据.帮助非常感谢!

As you can see it works for most cases, but when I enter a word FIRST and then a space followed by a number it evaluates it without the number. I am assuming this is happening because in the while loop is checking for only input.hasNext but it should be input.hasNextLine I believe to check the entire string. However I cannot have any arguments if I do that. Help much appreciated!

推荐答案

将正则表达式从: [A-Za-z] + 更改为 ^ [A-Za-z] +$ ,以防止在输入字符串中的任何地方出现数字

Change your regex from: [A-Za-z]+ to ^[A-Za-z]+$ in order to prevent numbers anywhere in the input-string

这篇关于防止用户在Java扫描仪中输入数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆