【发布时间】:2014-12-06 18:50:43
【问题描述】:
任务是让用户输入一笔钱作为赌注(这个数字必须大于0赌注>=1)。
1) 掷出两个骰子 (1-6)。
2) 计算它们的总和。如果这个总和等于 7,则用户赢 4 美元,如果输了,用户输 1 美元(例如:用户输入 5 美元作为初始赌注,赢 = 5+4=9$ 现在 - 输 = 5-1 =现在 4 美元)。
在用户玩完之后,我们需要询问他们是否想再玩一次,本质上是使用 while 语句再次运行程序。
我在第 43 行和第 50 行注释掉了要打印的语句,因为会发生这两行将在用户想要输入多少的初始问题之前打印(这就是我注释掉它们的原因)。
现在的问题是,在用户输入他/她想要下注的金额后,系统会计算他们赢/输的金额并打印出来。但是,它会跳过询问他们是否想再次播放的打印语句。为什么是这样?我知道出了点问题,因为最初程序跳过了第一个打印语句,直接进入第二个和第三个函数。有什么帮助吗?
谢谢!
//编辑:另外,如果还不是很明显,我对编程很陌生,所以请随时以任何方式批评我^^
//Dice Game
//10/11/14
import java.util.Random;
import java.util.Scanner;
public class diceGame2
{
//Instance Variables
private String play = "yes";
private int cash;
private int sum;
private int winnings;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
//Constructor
public diceGame2()
{
cash=0;
sum=0;
winnings=0;
}
public void game()
{
do
{
System.out.println("Please enter the amount of money you would like to bet");
cash=scan.nextInt();
if(cash<1)
{
System.out.println("Please enter a bet greater than 1$.");
cash=scan.nextInt();
}
}while((play.equals("yes")&&cash<0));
}
public int getDice()
{
int dice = rand.nextInt(6) + 1;
System.out.println("The number rolled was a" + " " + dice);
System.out.println();
return dice;
}
public int getSum(int d1, int d2)
{
sum = d1+d2;
System.out.println("Their sum is" + " " + sum + " " + "so...");
System.out.println();
return sum;
}
public int getWinnings(int sum)
{
if(sum==7)
{
cash += (4);
System.out.println("You have won" + " " + "4$.");
}
else
{
cash -= (1);
System.out.println("You have lost" + " " + "1$.");
}
System.out.println("You current have" + " " + cash + " " + "dollars left to bet");
return winnings;
}
public String getPlay()
{
System.out.println("Do you want to play again");
play = scan.next();
return play;
}
}//Class
//Dice Game Runner
//10/11/14
public class diceGameRunner
{
public static void main(String[]args)
{
String play = "yes";
while((play.equals("yes")))
{
diceGame2 d1 = new diceGame2();
int dice1, dice2, sum;
double money;
d1.game();
dice1 = d1.getDice();
dice2 = d1.getDice();
sum = d1.getSum(dice1, dice2);
money = d1.getWinnings(sum);
play = d1.getPlay();
}
}
}
【问题讨论】:
-
我只是略过这个,所以我还没有正确阅读它(还),但是你马上就有了一个带有无条件
break语句的while循环,所以循环只会执行一次。不知道这是否是您的问题,但它看起来像一个错误。换句话说,while的作用等同于if。 -
您需要发布您的主要方法或显示您的方法被调用的顺序
-
@bcsb1001 我放 break 语句的唯一原因是因为没有它,它会卡在 while 语句中。我知道由于 break 语句它只会运行一次,我只是不确定在询问 print 语句后如何让它离开循环。
-
尝试将
play.equals("yes"))||(play.equals("Yes")替换为play.equalsIgnoreCase("yes")&&cash<1,并去掉if和break。 -
这就是为什么教师让你在编码之前编写流程图。
标签: java while-loop dice