gpt4 book ai didi

java - 如何在Java中重新开始?

转载 作者:行者123 更新时间:2023-12-01 06:52:16 25 4
gpt4 key购买 nike

我有以下程序,我想要一个循环,询问用户是否想再次播放,以及是否想要该程序或播放重新开始。

import java.util.*;

public class Crapl {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
double budget;
int toGo = 1;
while (toGo == 1) {
Scanner input = new Scanner(System.in);
System.out.print("What is your budget");
budget = input.nextDouble();
play(budget);
}
}
// rool method

public static int roll() {
Random ran = new Random();
int dice1, dice2;

dice1 = ran.nextInt(6) + 1;
dice2 = ran.nextInt(6) + 1;
System.out.printf("\tYou rolled %d+%d=%d\t", dice1, dice2, dice1 + dice2);
return dice1 + dice2;
}

public static void play(double budget) {
int con, gamePoint, game;
int toGo = 1;
con = 0; //game will continue
double bet, budget2, userCredit = 0;
Scanner get = new Scanner(System.in);
gamePoint = 0;
budget2 = budget;

System.out.printf("You have $%.2f available balance, how much you want to bet:\n", budget);
bet = get.nextDouble();

while (bet > budget) {
System.out.printf("You ONLY have $%.2f available balance, how much you want to bet:\n", budget);
bet = get.nextDouble();
}

if (budget == 0.00) {
System.out.printf("you have $%.2f balance , so you cant play anymore ", budget);
}

budget = budget - bet;//withdraw amount from budget
game = roll(); //play game

switch (game) {
case 2:
case 3:
case 12:
con = -1; //game lost
System.out.printf("Sory you have lost the game. Your remaining balance is $%.2f\n", budget);
break;
case 7:
case 11:
con = 1;
System.out.printf("You won the game. Your remaining balance is $%.2f\n", budget + 2 * bet);
break;
default:
con = 0;
gamePoint = game;
System.out.printf("Game point is %d\n", gamePoint);
}

while (con == 0) {
System.out.printf("\nYou have $%.2f available balance, how much you want to bet:\n", budget);
bet = get.nextDouble(); //one loop
while (bet > budget) {
System.out.printf("You ONLY have $%.2f available balance, how much you want to bet:\n", budget);
bet = get.nextDouble();
}

budget -= bet; //withdraw the bet from budget
userCredit += bet; //keep adding total bet into userCredit.
game = roll();

if (game == 7) {
con = -1;
System.out.printf("\nSory you have lost the game. Your remaining balance is $%.2f\n", budget);
} else if (game == gamePoint) {
con = 1;
budget2 += userCredit;
System.out.printf("\nYou have won the game. Your remaining balance is $%.2f\n", budget2);

System.out.printf("Would you like to play again?\n");
System.out.printf("If yes enter 1 0 otherwise\n");
toGo = get.nextInt();
}
}
}
}

最佳答案

首先,您正在静态地执行所有操作。将所有变量等放置在一个对象中。在您的 main 方法中,在 do while 循环中实例化该对象。

在循环结束时,询问玩家是否要重播,然后根据答案循环。此时,您可以根据需要重新初始化该对象。

关于java - 如何在Java中重新开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22232072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com