java 如何确保用户不输入字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12614817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:33:48  来源:igfitidea点击:

How to make sure user doesn't enter letters

javainputuser-input

提问by Matt McCarthy

In my program the user has to choose what they want to do and then hit the number next to the choice and then hit enter.

在我的程序中,用户必须选择他们想要做的事情,然后点击选项旁边的数字,然后点击 Enter。

Right now I have it so that any number that isn't a choice will give an error but now I want to make sure it says error if the user types in a letter for example "fadhahafvfgfh"

现在我有了它,所以任何不是选择的数字都会出错,但现在我想确保如果用户输入一个字母,例如“fadhahafvfgfh”,它会显示错误

here is my code...

这是我的代码...

import java.util.Scanner;

public class AccountMain {


    public static void selectAccount(){


        System.out.println("Which account would you like to access?");
        System.out.println();
        System.out.println("1 = Business Account ");
        System.out.println("2 = Savings Account");
        System.out.println("3 = Checkings Account");
        System.out.println("4 = Return to Main Menu");

        menuAccount();


    }

    public static void menuAccount(){

        BankMain main = new BankMain();
        BankMainSub sub = new BankMainSub();
        BankMainPart3 main5 = new BankMainPart3();

        Scanner account = new Scanner(System.in);

        int actNum = account.nextInt();

        if (actNum == 1){

            System.out.println("*Business Account*");
            sub.businessAccount();
        }

        else if (actNum == 2){

            System.out.println("*Savings Account*");
            main.drawMainMenu();
        }

        else if (actNum == 3){

            System.out.println("*Checkings Account*");
            main5.checkingsAccount();
        }

        else if (actNum == 4){
            BankMain.menu();

        }

    }
}

回答by Amit Deshpande

You can use Scanner#hasNextInt()for this.

为此,您可以使用Scanner#hasNextInt()

if(account.hasNextInt())
  account.nextInt();

Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt() method. The scanner does not advance past any input.

如果可以使用 nextInt() 方法将此扫描器输入中的下一个标记解释为指定基数中的 int 值,则返回 true。扫描仪不会通过任何输入。

If user does not enter valid then you can say bye bye see you next time like below.

如果用户没有输入有效,那么你可以说再见,下次见,如下所示。

    int actNum = 0;
    if(account.hasNextInt()) {
        //Get the account number 
        actNum = account.nextInt();
    }
    else
    {
        return;//Terminate program
    }

Else you can show error message and ask user to retry for valid account number.

否则,您可以显示错误消息并要求用户重试有效帐号。

    int actNum = 0;
    while (!account.hasNextInt()) {
        // Out put error
        System.out.println("Invalid Account number. Please enter only digits.");
        account.next();//Go to next
    }
    actNum = account.nextInt();

回答by Rohit Jain

Scanner account = new Scanner(System.in);
int count = 0;
while (true and count < 3) {
    if (!account.hasNextInt()) {
        int actNum = account.nextInt();
        break;
    } else {
         System.out.println("Enter an integer");
         count++;
         account.next();
    }
}

回答by Amar Magar

i think the accepted answer is correct, but we should make use of java features like exception handling in our code

我认为接受的答案是正确的,但我们应该在我们的代码中使用诸如异常处理之类的 Java 功能

// so our code should look like this

// 所以我们的代码应该是这样的

public static void main(String[] args) {

    int choice=0;
    Scanner scanner = new Scanner(System.in);
    StringReverse objReverse = new StringReverse();

    System.out.println("Menu");
    System.out.println("1.Reverse String");
    System.out.println("2.Exit");

    do {
            System.out.println("Enter your choice");
            try {
                choice = scanner.nextInt();
                switch(choice) {

                     case 1 :
                            System.out.println("Enter the string to reverse");
                            String inputString = new String();
                            inputString = scanner.next();
                            String reversedString = objReverse.reverse(inputString );
                            System.out.println("Reversed String is " + reversedString);
                            break;

                     case 2 :
                            System.out.println("Exiting...");
                            return;

                     default :
                            System.out.println("Default choice");
                            break;
               }
            } catch(Exception e) {
                    System.out.println("Please enter valid integer input");
                    scanner.next();
            }
   } while(choice != 2);
}

回答by PermGenError

You can use Scanner.hasNextInt()or Integer.parseInt().

您可以使用Scanner.hasNextInt()Integer.parseInt()

Scanner account = new Scanner(System.in);
String actNum = account.next();
try {
    Integer.parseInt(actNum);
} catch(ParseException ex) {
    sysout("please enter only numeric values")
}

回答by st0le

The Scanner has a hasNextInt()function that returns true if the next token is a Integer. So before calling nextInt()validate if hasNextInt()is true. If it fails, show a message to the user asking him to enter an integer. Note, The Integer doesn't necessarily needs to fall in your required range, so make sure you also have a final elseto inform the user the number he entered was invalid.

Scanner 有一个hasNextInt()函数,如果下一个标记是整数,则该函数返回 true。所以在调用之前nextInt()验证是否hasNextInt()为真。如果失败,向用户显示一条消息,要求他输入一个整数。请注意,整数不一定需要落在您要求的范围内,因此请确保您还有一个最终else通知用户他输入的数字无效。

Tip: Use Switch Case.

提示:使用 Switch Case。