-2

我正在尝试创建一个计算机模拟二十一点游戏的金钱损失。但是我遇到了一个错误,如果我在其中一个提示中输入小于零的值,程序必须在警告小于零之前通过所有其他提示。

有没有办法立即警告小于零的值,而不必一遍又一遍地为每个 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");
        }
    }
}
4

2 回答 2

1

模块化。创建一个方法(甚至是一个类),它接受输入并仅在满足条件时才接受它。例如

 private int myIntGetter(String caption, boolean forcePositive) {
    System.out.println(caption);
    Scanner input = new Scanner(System.in);
    int intValue = input.nextInt();
    while ((forcePositive) && (intValue <=0)) {
      System.out.println("Number must be greater than \0");
      System.out.println(caption);
      intValue = input.nextInt();
    }
    // here intValue is valid
    return intValue;
  }
于 2012-12-26T23:59:01.540 回答
0

如果您不关心对用户友好:

do{
   System.out.println("Enter number of rounds.  Rounds must greater than zero.");
   setRounds(input.nextInt());
}while( getRounds()<=0);

您可以为用户必须输入的每件事执行此操作。它又快又脏。

于 2012-12-26T23:57:23.213 回答