我们正在学习选择,并且必须为摇滚,纸张,剪刀游戏编写程序。我的程序运行没有错误,但它只打印“计算机是____。你是____。”我无法弄清楚为什么它不打印你赢/输?这是一个平局声明。
// Solution for exercise 3.17
import java.util.Scanner;
public class PA6c {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Get user input for number associated with rock, paper, or scissor
System.out.print("Enter a number 0-2: ");
int userNumber = input.nextInt();
// Generate random number for computer
int compNumber = (int)(Math.random() * 10);
// Declare rock, paper, and scissor
int scissor = 0;
int rock = 1;
int paper = 2;
// Determine what the computer is
if (compNumber == scissor) {
System.out.print("The computer is scissor. ");
}
else if (compNumber == rock) {
System.out.print("The computer is rock. ");
}
else {
System.out.print("The computer is paper. ");
}
// Determine what the user is
if (userNumber == scissor) {
System.out.print("You are scissor. ");
}
else if (userNumber == rock) {
System.out.print("You are rock. ");
}
else {
System.out.print("You are paper. ");
}
// Determine who won
if (compNumber == scissor) {
if (userNumber == scissor) {
System.out.println("It is a draw.");
}
else if (userNumber == rock) {
System.out.println("You win.");
}
else if (userNumber == paper) {
System.out.println("You lose.");
}
}
else if (compNumber == rock) {
if (userNumber == scissor) {
System.out.println("You lose.");
}
else if (userNumber == rock) {
System.out.println("It is a draw.");
}
else if (userNumber == paper) {
System.out.println("You win.");
}
}
else if (compNumber == paper) {
if (userNumber == scissor) {
System.out.println("You win.");
}
else if (userNumber == rock) {
System.out.println("You lose.");
}
else if (userNumber == paper) {
System.out.println("It is a draw.");
}
}
}
}
答案 0 :(得分:0)
问题在于您尝试获取随机数的方式。在任何时候你都需要{0,1,2}
的随机数,但Math.Random()*10
会给你{0,1,2,3,4,5,6,7,8,9}
范围内的数字,所以你的目的在这里被打败了。因此,请确保compNumber
始终是{0,1,2}
之一。
用此替换你的随机数生成线,
Random rand = new Random();
compNumber = rand.nextInt(0 , 3); // will give you 0 or 1 or 2