检查用户输入的数字 [英] Checking user input is a number
本文介绍了检查用户输入的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要检查用户输入.我有一个菜单,我需要用户选择数字0-4,但是如果用户选择字母而不是数字,那么我只会得到InputMismatchException.因此,我试图验证用户输入了一个数字.这是我的代码:
I need to check users input. I have a menu and I need the user to select numbers 0-4 but if the user selects a letter instead of a number then I just get a InputMismatchException. So I am trying to validate that the user entered a number. Here is my code:
public class TestBankAccount {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
ArrayList<BankAccount> list = new ArrayList<BankAccount>();
int choice;
do {
System.out.println("1. Deposit money");
System.out.println("2. Withdraw money");
System.out.println("3. Check balance");
System.out.println("4. Create new account");
System.out.print("Your choice, 0 to quit: ");
choice = input.nextInt();
switch (choice) {
case 1:
depositMoney(list);
break;
case 2:
withdrawMoney(list);
break;
case 3:
checkBalance(list);
break;
case 4:
createNewAccount(list);
break;
case 0:
System.out.println("Thank you for trusting us with your banking needs!");
break;
default:
System.out.println("Invalid option is selected!");
}
System.out.println();
} while (choice != 0);
if (list.size() > 0) {
displayResults(list);
}
}
我正在考虑做while(选择!= 0&&选择!= input.hasNextInt())之类的事情;但我得到一个错误.有什么想法吗?
I was thinking to do something like while (choice != 0 && choice != input.hasNextInt()); but I get an error. Any ideas?
推荐答案
您可以执行以下操作:
int choice = 0 ;
try{
choice = Integer.parseInt(input.next());
}
catch(NumberFormatException e)
{
System.out.println("invalid value enetered");
}
// Now you can check if option selected is between 1 & 4
// and throw some custom exception
这篇关于检查用户输入的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文