java - 2-player dice game on how to compare the die and get to 20 points
问题描述
Each player rolls two dice They compare the highest number on each roll. The player whose number is greater earns 2 points. They compare the lowest number on each roll. The player whose number is greater earns 1 point. If the numbers are a tie, no points are awarded. The first player to 20 total points wins. how would I do the compare part? This the code I have so far
import java.util.Scanner;
import java.util.Random;
public class DiceGame
{
public static void main(String[] args) // method 1
{
String again = "y"; // To control the loop
int die1; // To hold the value of die #1
int die2; // to hold the value of die #2
int die3;
int die4;
// Create a Scanner object to read keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create a Random object to generate random numbers.
Random rand = new Random();
// Simulate rolling the dice.
while (again.equalsIgnoreCase("y"))
{
System.out.println("Rolling the dice...");
die1 = rand.nextInt(6) + 1;
die2 = rand.nextInt(6) + 1;
System.out.println("Player 1's values are:");
System.out.println(die1 + " " + die2);
die3 = rand.nextInt(6) + 1;
die4 = rand.nextInt(6) + 1;
System.out.println("Player 2's values are:");
System.out.println(die3 + " " + die4);
//method 2 = comparing the numbers
public static void compareRoll(int die1, die2, die3, die4)
{
{
if(die1 > die2 && die3 > die4)
else if(die1 < die2 && die3 < die4)
else
}
}
//method 3 = getting total number of scores
System.out.print("Roll them again (y = yes)? ");
again = keyboard.nextLine();
}
}
}
解决方案
我看到这样的事情:
public void compareDices(int die1, int die2, int die3, int die4)
int firstMax = Math.max(die1, die2);
int secMax = Math.max(die3, die4);
if(firstMax > secMax) {
// add 2 points to first player
} else if(firstMax < secMax) {
// add 2 points to sec player
}
int firstMin = Math.min(die1, die2);
int secMin = Math.min(die3, die4);
if(firstMin > secMin) {
// add 1 point to first player
} else if(firstMin < secMin) {
// add 1 point to sec player
}