【发布时间】:2015-05-30 12:54:55
【问题描述】:
这个程序的目的是制作一个石头剪刀布游戏。我已经成功地做到了,但是无论我尝试什么,我都无法让它循环。我试过了:
while (index = 0)
while (index < gamesCount)
但是,虽然我的索引为 0 且条件为 while (index != 0),但它似乎是运行程序的唯一条件,但无论如何它都不会循环。如何让我的游戏循环播放?
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random randomGen = new Random();
//Variables
String player1;
int cpu;
int start = 1;
int end = 3;
int index = 0;
// 1 = Rock | 2 = Scissors | 3 = Paper
//Code
System.out.println("Welcome to Rock, Paper, Scissors!");
while (index != 0) {
System.out.print("Rock, Paper, or Scissors?: ");
player1 = in.nextLine();
cpu = randomGen.nextInt(3);
System.out.println(cpu);
if (player1.equals("Rock") && (cpu == 2)) {
System.out.println("You lose!");
} else if (player1.equals("Rock") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Rock") && (cpu == 0)) {
System.out.println("Draw!");
}
// --------------------
if (player1.equals("Scissors") && (cpu == 2)) {
System.out.println("Draw!");
} else if (player1.equals("Scissors") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Scissors") && (cpu == 0)) {
System.out.println("You lose!");
}
//---------------------
if (player1.equals("Paper") && (cpu == 2)) {
System.out.println("You lose!");
} else if (player1.equals("Paper") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Paper") && (cpu == 0)) {
System.out.println("Draw!");
}
}
}
}
【问题讨论】:
-
while (index < gamesCount)似乎是一个不错的选择 - 为什么它没有达到你想要的效果?如果您使用这种方法,您需要在每个循环(即循环内的index++)的索引中添加一个(increment),然后将gamesCount定义为您的循环数想要(例如int gamesCount = 10;) -
P.S.目前在您的程序中,
index始终为零,因此index != 0将始终为 false,因此程序永远不会进入该代码块。当您尝试while (index = 0)时,您可能意味着while(index == 0) - which would make the game loop infinitely at the moment. You need to understand that=` 是Java 中的赋值运算符(即给变量一个值),==是相等比较运算符(即测试两个值相同)。
标签: java loops conditional-statements