**6.30(游戏:双骰子赌博)执双骰子游戏是赌场中非常流行的骰子游戏。编写程序,玩这个游戏的一个变种,如下所描述: 执两个骰子。每个骰子有六个面,分别表示值1,2,…,6。检查这两个骰子的和。如果和为2、3或12(称为掷骰子(crap)),你就输了;如果和是7或者11(称作自然(natural)),你就赢了;但如果和是其他数字(例如:4、5、6、8、9或者10),就确定了一个点。继续掷骰子,直到掷出一个7或者掷出和刚才相同的点数。如果掷出的是7,你就输了。如果掷出的点数和你前一次掷出的点数相同,你就赢了。程序扮演一个独立的玩家。
下面是一些运行示例:
You rolled 5 + 6 = 11
You win
You rolled 1 + 2 = 3
You lose
You rolled 4 + 4 = 8
point is 8
You rolled 6 + 2 = 8
You win
You rolled 3 + 2 = 5
point is 5
You rolled 2 + 5 = 7
You lose
**6.30(Game: craps)Craps is a popular dice game played in casinos. Write a program to play a variation of the game, as follows:Roll two dice. Each die has six faces representing values 1, 2, . . ., and 6, respectively. Check the sum of the two dice. If the sum is 2, 3, or 12 (called craps), you lose; if the sum is 7 or 11 (called natural), you win; if the sum is another value (i.e., 4, 5, 6, 8, 9, or 10), a point is established. Continue to roll the dice until either a 7 or the same point value is rolled. If 7 is rolled, you lose. Otherwise, you win. Your program acts as a single player.
Here are some sample runs.
You rolled 5 + 6 = 11
You win
You rolled 1 + 2 = 3
You lose
You rolled 4 + 4 = 8
point is 8
You rolled 6 + 2 = 8
You win
You rolled 3 + 2 = 5
point is 5
You rolled 2 + 5 = 7
You lose
下面是参考答案代码:
public class CrapsQuestion30 {
public static void main(String[] args) {
int sumOfTwoDice,firstDie,secondDie,point;
firstDie = rollDie();
secondDie = rollDie();
sumOfTwoDice = firstDie + secondDie;
if(sumOfTwoDice == 2 || sumOfTwoDice == 3 || sumOfTwoDice == 12)
{
System.out.printf("You rolled %d + %d = %d\n",firstDie,secondDie,sumOfTwoDice);
System.out.println("You lose");
}
else if(sumOfTwoDice == 7 || sumOfTwoDice == 11)
{
System.out.printf("You rolled %d + %d = %d\n",firstDie,secondDie,sumOfTwoDice);
System.out.println("You win");
}
else
{
point = sumOfTwoDice;
System.out.printf("You rolled %d + %d = %d\n",firstDie,secondDie,sumOfTwoDice);
System.out.printf("point is %d\n", point);
do {
firstDie = rollDie();
secondDie = rollDie();
sumOfTwoDice = firstDie + secondDie;
}while(sumOfTwoDice !=7 && sumOfTwoDice != point);
System.out.printf("You rolled %d + %d = %d\n",firstDie,secondDie,sumOfTwoDice);
if(sumOfTwoDice == point)
System.out.println("You win");
else if(sumOfTwoDice == 7)
System.out.println("You lose");
}
}
public static int rollDie() {
return (int)(Math.random() * 6 + 1);
}
}
运行效果:
注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等