我正在尝试创建一个计算机模拟二十一点游戏的金钱损失。但是我遇到了一个错误,如果我在其中一个提示中输入小于零的值,程序必须在警告小于零之前通过所有其他提示。
有没有办法立即警告小于零的值,而不必一遍又一遍地为每个 if 放置相同的 else 语句?
private void menu()
{
boolean NonNumeric=false;
//This is so a different exception is thrown for the minimum stakes since it's a float.
boolean isDecimal=false;
while(getRounds()<=0 || getPlayers()<=0 || getStakes()<=0 )
{
try
{
Scanner input = new Scanner(System.in);
if(getRounds()<=0)
{
System.out.println("Enter number of rounds.");
setRounds(input.nextInt());
}
if(getPlayers()<=0)
{
System.out.println("Enter number of players.");
setPlayers(input.nextInt());
}
if(getStakes()<=0)
{
System.out.println("Enter minimum stakes.(Note: All players bet minimum only)");
isDecimal=true;
setStakes(input.nextFloat());
}
}
catch (InputMismatchException e ) //In case some idiot enters a letter or symbol.
{
//This if statement is so that a different message comes if the invalid entry is a float.
if(isDecimal==true)
{
System.out.println("Entry must be a number. Not a letter or symbol. Try Again.\n");
}
else
{
System.out.println("Entry must be a whole number. Not a letter, decimal, or symbol. Try Again.\n");
}
/*This boolean is so that the below if statement does not run if the user enters a letter
since the integer defaults back to a 0 on exception.*/
NonNumeric = true;
}
if(getRounds()<=0 || getPlayers()<=0 || getStakes()<=0)
{
System.out.println("Number must be greater than 0.\n");
}
}
}