【发布时间】:2013-12-08 21:16:24
【问题描述】:
我正在尝试用 java 制作一个石头剪刀布游戏。我这里有我的基本代码
import java.util.Scanner;
import java.util.Random;
public class RPSBase
{
public static void main(String args[])
{
Random rndm = new Random();
int c =0 + rndm.nextInt(3);
Scanner c2 = new Scanner(System.in);
String pc = c2.next();
switch (c)
{
case 1:
String choice = "r";
char ch = choice.charAt(0);
break;
case 2:
choice = "p";
ch = choice.charAt(0);
break;
case 3:
choice = "s";
ch = choice.charAt(0);
break;
}
switch (ch)
{
case 'r':
if (pc == "r")
System.out.println("It's a tie");
else if (pc == "p")
System.out.println("win");
else if (pc == "s")
System.out.println("lose");
break;
case 'p':
if (pc == "p")
System.out.println("It's a tie");
else if (pc == "s")
System.out.println("win");
else if (pc == "r")
System.out.println("lose");
break;
case 's':
if (pc == "s")
System.out.println("It's a tie");
else if (pc == "r")
System.out.println("win");
else if (pc == "p")
System.out.println("lose");
break;
}
}
}
由于某种原因,当我编译程序时出现此错误
1 error found:
File: C:\Users\Larry\RPSBase.java [line: 26]
Error: ch cannot be resolved to a variable
为什么会出现此错误,如何解决?我也试过 switch(choice) 也没有用。
【问题讨论】:
-
考虑
ch是在哪里声明的?变量有作用域。它们只能在该范围内使用。