这是一个模仿骰子游戏的程序。规则是,如果你掷7或11,你就赢了。如果你掷出2、3或12,你就输了。如果你滚动其他任何东西,你会得到一个“点”,并被允许再次滚动。如果你分配2分,你也会赢。
我在这里遇到的问题是积分系统。我不知道如何存储点,然后退出循环,并提示用户再次滚动以重新进入循环。
import javax.swing.JOptionPane;
public class DiceGame {
public static void main(String args[ ]) {
// declarations
int dieNumber1,
dieNumber2,
point,
score;
// initializations
dieNumber1 = (int)(Math.random( ) * 6 + 1);
dieNumber2 = (int)(Math.random( ) * 6 + 1);
score = dieNumber1 + dieNumber2;
// executable statements
for (int i = 0; i < 10000; i++)
{
System.out.println ("Roll the die");
System.out.println ("You rolled a " + score);
if (score == 11 || score == 7)
{
System.out.println ("You Win!");
break;
}
if (score == 2 || score == 3 || score == 12)
{
System.out.println ("You Lose.");
break;
}
if (score == 4 || score == 5 || score == 6 || score == 8 || score == 9 || score == 10)
{
point = 1;
System.out.println ("You got a point.");
}
}
System.exit(0);
} // end of the main method
} // end of the class
发布于 2018-10-10 04:46:16
您需要将初始化移动到循环中,等待一些用户输入再次滚动,如果它们得到一个点,则增加点数。
这应该会满足您的需求
import javax.swing.JOptionPane;
import java.util.Scanner;
public class DiceGame {
public static void main(String args[ ]) {
// declarations
int dieNumber1 = 0,
dieNumber2 = 0,
point = 0,
score = 0;
Scanner scanner = new Scanner(System.in);
// executable statements
// Repeat until score is 2 (or break is called)
while( point < 2 ){
// initializations
dieNumber1 = (int)(Math.random( ) * 6 + 1);
dieNumber2 = (int)(Math.random( ) * 6 + 1);
score = dieNumber1 + dieNumber2;
System.out.println ("Roll the die");
System.out.println ("You rolled a " + score);
if( score == 11 || score == 7 ){
System.out.println ("You Win!");
break;
}
if( score == 2 || score == 3 || score == 12 ){
System.out.println ("You Lose.");
break;
}
if( score == 4 || score == 5 || score == 6 || score == 8 || score == 9 || score == 10 ){
point = point + 1; // You could use point++ or point += 1 as well
System.out.println ("You got a point. Total number of points: " + point);
if( point == 2 ){
System.out.println("You Win!");
}
else{
// Wait until user presses Enter, then roll again
System.out.println ("Press Enter to roll again.");
scanner.nextLine();
scanner.reset();
}
}
}
System.exit(0);
} // end of the main method
} // end of the class
https://stackoverflow.com/questions/52728367
复制相似问题