下面是正常工作的代码:
import java.util.Scanner;
import java.util.Random;
public class game {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] rps = {"rock","paper","scissors"};
String computerMove = rps[new Random().nextInt(rps.length)];
for(int i=0;i<2;i++) {
System.out.println("Please enter your move (rock, paper or scissors)");
String playerMove = scanner.nextLine();
if(playerMove.equals(computerMove)) {
System.out.println("It's a tie. Computer chose also "+computerMove);
}
else if (playerMove.equals("rock")) {
if (computerMove.equals("scissors")) {
System.out.println("You've won. Computer chose "+computerMove);
}
else {
System.out.println("You loose. Computer chose "+ computerMove);
}
}
else if (playerMove.equals("paper")) {
if (computerMove.equals("rock")) {
System.out.println("You've won. Computer chose "+computerMove);
}
else {
System.out.println("You loose. Computer chose "+computerMove);
}
}
else if (playerMove.equals("scissors")) {
if (computerMove.equals("paper")) {
System.out.println("You've won. Computer chose "+computerMove);
}
else {
System.out.println("You loose. Computer chose "+computerMove);
}
}
}
}
但我还想包括回合,这样用户就可以选择他想玩多少回合:
import java.util.Scanner;
import java.util.Random;
public class game {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] rps = {"rock","paper","scissors"};
String computerMove = rps[new Random().nextInt(rps.length)];
System.out.println("How many rounds you wanna play?");
int rounds = scanner.nextInt();
for(int i=0;i<rounds;i++) {
System.out.println("Please enter your move (rock, paper or scissors)");
String playerMove = scanner.nextLine();
if(playerMove.equals(computerMove)) {
System.out.println("It's a tie. Computer chose also "+computerMove);
}
else if (playerMove.equals("rock")) {
if (computerMove.equals("scissors")) {
System.out.println("You've won. Computer chose "+computerMove);
}
else {
System.out.println("You loose. Computer chose "+ computerMove);
}
}
else if (playerMove.equals("paper")) {
if (computerMove.equals("rock")) {
System.out.println("You've won. Computer chose "+computerMove);
}
else {
System.out.println("You loose. Computer chose "+computerMove);
}
}
else if (playerMove.equals("scissors")) {
if (computerMove.equals("paper")) {
System.out.println("You've won. Computer chose "+computerMove);
}
else {
System.out.println("You loose. Computer chose "+computerMove);
}
}
}
}
你的文本,那么这个的输出是:你想玩几局?2请输入你的移动(石头,布或剪刀)请输入你的移动(石头,布或剪刀)石头你赢了,电脑选择了剪刀
我期待它能像以前一样平稳运行,但不知何故,与轮系统,它不工作
2条答案
按热度按时间q8l4jmvw1#
移动**字符串计算机移动= rps[新随机().nextInt(rps.长度)];**进入for循环。
正确代码:
iqjalb3h2#
问题是这样的
它应该是这样的:
这是因为
nextLine()
方法由于先前从(you键入一个数字和
Enter
)并返回“"(空
String
)。由于
playerMove
的值为空,所以三个都不匹配,你可以在google中找到更多关于next()和nextLine()区别的细节。另外,你应该尝试调试,就像David说的那样,因为这是编码中最重要也是最有趣的部分。