我有一项任务,因为这要求我创建一个老虎机程序,该程序将继续运行,直到用户用完钱或按零。我无法弄清楚什么样的循环以及用于此循环的变量以使其工作。目前我已经拥有了程序其余部分所需的所有if语句,但是什么样的循环给我带来了麻烦。我认为while循环是可行的方法,但每次实现while循环时,程序都不会停止执行。
import java.util.*;
public class SlotMachine {
public static final int BALANCE=10;
public static void main(String[] args) {
int bet, remBal=0,winnings1,winnings2;
int slot1, slot2, slot3;
Random generator = new Random();
System.out.println("Starting Balance = $10:00");
Scanner kbd=new Scanner(System.in);
System.out.print("Enter a bet $");
bet=kbd.nextInt();
if (bet>0&&bet<BALANCE){
slot1 = generator.nextInt(10);
slot2 = generator.nextInt(10);
slot3 = generator.nextInt(10);
slot1 = 3;
slot2 = 3;
slot3 = 3;
System.out.println(slot1+" "+slot2+" "+slot3);
if(slot1==slot2&&slot2==slot3&&slot1==slot3){
System.out.println("You win: "+(double)(slot1+1)*bet);
winnings1=(slot1+1)*bet;
remBal=BALANCE-bet+winnings1;
}else if (slot1==slot2||slot2==slot3){
System.out.println("You win: "+(double)(slot2*bet)/2);
winnings2=(slot2*bet)/2;
remBal=BALANCE-bet+winnings2;
}else{
System.out.println("Balance "+(double)(BALANCE-bet));
}
}else if(bet==0){
System.out.println("You earned"+remBal);
}kbd.close();
}
}
答案 0 :(得分:1)
您的问题是请求下注的代码在处理它的块之外。如果您将其转换为while
循环,那么您永远不会要求用户进行另一次下注;因此无限循环。
您可能想要的是do-while
循环。这意味着请求下注的代码至少执行一次,并且在块结束时检查测试而不是开始。
所以代码的结构应该是:
do {
// ask for bet
if (bet > 0) {
// process bet
}
} while (bet > 0 && balance > 0);
// print out results
答案 1 :(得分:0)
您可以尝试此代码
System.out.println("Starting Balance = $10:00");
Scanner kbd = new Scanner(System.in);
System.out.print("Enter a bet $");
bet = kbd.nextInt();
while (bet != 0) {
// you code
System.out.print("Enter a bet $");
bet = kbd.nextInt();
}
kbd.close();
答案 2 :(得分:0)
public class SlotMachine {
public static final int BALANCE=10;
public static void main(String[] args) {
int bet, remBal=BALANCE,winnings1,winnings2;
int slot1, slot2, slot3;
Random generator = new Random();
System.out.println("Starting Balance = $10:00");
Scanner kbd=new Scanner(System.in);
System.out.print("Enter a bet $");
bet=kbd.nextInt();
while (bet>0 && bet<remBal){
//Your code for checking wins
bet = kbd.nextInt();
}
kbd.close();
}