我正在练习 java 银行帐户中的一些简单任务,需要有关代码块的建议,如何编写? 这是一个例子,如果用户输入字符串或一些字母而不是数字来打印“请输入数字”,如何输入 Else if block amount == String,例如,很多 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 + " €");
}
最佳答案
在将其存储到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 次就退出程序,则不会提供正确的值。
关于Java 初学者需要建议吗?如果(金额==字符串)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32539027/