在 类 (Java) 中使用扫描仪循环

Using a scanner loop across classes (Java)

我正在尝试在我的主要方法中使用扫描仪循环作为输入 class 中的方法。我不断收到此错误:

Exception in thread "main" java.lang.NullPointerException
at Blackjack.Input.getBet(Input.java:27)
at Blackjack.BlackJackGame.main(BlackJackGame.java:23)

这是循环(这个循环在一个单独的 class 中):

    public int getBet(int cash) {
    Scanner sc = new Scanner(System.in);
    int bet = sc.nextInt();
        while (bet > cash) {
            outputter.cannotBet();
            outputter.askBet();
            bet=sc.nextInt();
        }
    return bet;
}

这里是我在主要方法中调用它的地方:

user.setBet(input.getBet(user.getCash()));

基本上,不应允许用户下注超过他或她所拥有的钱,并且当赌注超过他或她所拥有的现金时,它应该循环并要求用户重新输入一个数字.非常感谢任何帮助。

尝试替换这个

 public int getBet(int cash) {
Scanner sc = new Scanner(System.in);
int bet = sc.nextInt();
    while (bet > cash) {
        outputter.cannotBet();
        outputter.askBet();
        bet=sc.nextInt();
    }
return bet;
}

有了这个

 public int getBet(int cash) {

Scanner sc = new Scanner(System.in);
    int bet = 0;//or you could put this as a global variable, but its considered "bad practise"
    while (bet > cash) {
        bet = sc.nextInt();
        outputter.cannotBet();
        outputter.askBet();
        continue;
    }
return bet;
}

希望对您有所帮助

我让它更简单了。请试试这个。 我从我的代码中删除了其他未知方法。

    Scanner sc = new Scanner(System.in);
    int bet = 0;
    do {
          bet=sc.nextInt();
    } while (bet > cash);

    return bet;

假设您将现金作为 100,然后您输入 200 作为赌注,它会再次询问输入。如果下注为 20,则条件为假且 return 值。希望对你有帮助。