我在用户和计算机之间创建了一个骰子游戏,该游戏循环10次回合-但是如果其中一个回合是平局-它将询问您是否要再次玩并重新开始游戏。我在最后一部分遇到问题,因为游戏现在会随机迭代。有什么建议吗?
import java.util.Random;
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("User vs. Computer Dice Game");
boolean Correct = false;
boolean Replay = false;
while(Replay == true) {
}
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for(int i =1; i<11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6)+1;
System.out.println("User rolled: "+usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6)+1;
System.out.println("Computer rolled: "+computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if(usernum == computernum) {
System.out.println("It\'s a tie!");
System.out.println("Do you want to play again? (Y/N) ");
System.out.println();
if (a.equalsIgnoreCase("N")){
Replay = true;
}
else {
Correct = false;
}
}
}
}
System.out.println();
}
}
}
答案 0 :(得分:1)
一些注意事项:
主循环具有“ for(int i = 1; i <11; i ++)”。
在该循环的内部(这是平局),您询问是否要再次玩,但是没有结束循环的内容,因此内部的for循环将继续播放直到您打11。
您可能需要添加break语句来终止for循环。
实际上,您最好放弃循环,然后在while循环的顶部再次询问问题:
while(Correct == false) {
System.out.println("Do you want to play again? ");
String a = in.nextLine();
System.out.print(a);
if (a.equals("yes")) {
for (int i = 1; i < 11; i++) {
Random rand = new Random();
int usernum = rand.nextInt(6) + 1;
System.out.println("User rolled: " + usernum);
Random rand2 = new Random();
int computernum = rand2.nextInt(6) + 1;
System.out.println("Computer rolled: " + computernum);
if (usernum > computernum) {
System.out.println("User wins");
System.out.println();
}
if (computernum > usernum) {
System.out.println("Computer wins");
System.out.println();
}
if (usernum == computernum) {
System.out.println("It's a tie!");
// Exit early from the for loop:
break;
}
}
}
else
{
Correct = true;
}
}