我在java银行帐户中练习一些简单的任务,需要建议代码块,如何写这个? 这是一个例子,如果块数= =字符串,如果用户输入字符串或一些字母而不是数字来打印“请输入一个数字”,例如,许多thx
case 2:
int amount = 0;
System.out.println("Amount to withdraw:");
amount = in.nextInt();
if(amount <= 0)
{
System.err.println("you cannot withdraw negative amount!");
}
else if(amount > balans)
{
System.err.println("Not enough money on account!");
}
else if(...) // Here l need that
{
System.err.println("please enter a number instead of letters");
}
else
{
balans-=amount;
System.out.println("You have successfully withdrawn " + amount + " €");
}
答案 0 :(得分:2)
只需检查用户提供的值类型,然后再将其存储在amount
中。您可以使用in.hasNextInt
。如果不是Integer
则要求用户再次连接正确的值。
你可以试试像
这样的东西System.out.print("write Integer: ");
while(!in.hasNextInt()){ //used didn't provide valid value
String value = in.next(); //lets consume it so Scanner can read and test next value
System.out.println(value +" is not considered valid Integer.");
System.our.print("please try again: ");
}
//here we are sure that user provided proper integer
amount = in.nextInt();
//and now we can proceed with rest of code
if(amount <= 0){
...
}
您还可以添加尝试计数器,用户将无法提供正确的值,让我们说3次尝试退出程序。
答案 1 :(得分:2)
如果用户输入的不是数字,那么这一行:
amount = in.nextInt();
将抛出异常(InputMismatchException
)。有两种选择:
将调用(和以下测试)包含在try
块中,并catch
例外。您可以在catch块中打印“this is not number”消息。
在in.hasNextInt()
之前致电nextInt
,看看nextInt()
来电是否成功。
顺便说一下,如果他/她输入“1.00”或“$ 1”,则“请输入数字而不是字母”这一消息会使真实ATM的真实用户感到困惑。他们可能会说“我输入一个号码.Stoopop机器!”
您需要仔细考虑非IT人员应该理解的消息的措辞。
(实际上,任何人都是。只是IT人员习惯于插入模糊或错误措辞的错误信息......因为他们看到了很多错误信息。)
答案 2 :(得分:0)
您可以使用简单的正则表达式。
String regex = "\\d+";
String test = "ss";
if(!test.matches(regex))
{
System.out.println("Please enter integers.");
}
output =请输入整数。