好的,所以我做了一个java程序,你从用户输入石头纸或剪刀,然后计算机将生成随机选择,并相应地打印结果。程序逻辑(我的意思是用户和对手选择的比较)工作正常。我设置了一个do-while循环,用户输入'Y'然后会有第二个匹配,这将持续到用户终止循环。但是,我收到错误“无法找到符号:变量ans”
所以有人可以解释一下,为什么我会收到这个错误以及如何修复它?
以下是代码:
import java.lang.Math;
import java.util.Scanner;
公共类STP
{
public static void main (String args[])
{
do {
String c , ans ;
Scanner in = new Scanner(System.in);
System.out.println("Stone , Paper or Scissor ?");
System.out.println("Press s for stone , p for paper and sc for scissor ");
System.out.println("Enter Your Choice");
c=in.nextLine();
int max,min=0;
int rand = 0;
max=3;
min=1;
rand= min +(int)(Math.random() * ((max-min)+1));
System.out.println("Rand = " + rand);
switch(c)
{
case "s" :
if (rand==1){
System.out.println("User's Choice : Stone");
System.out.println("Opponent's Choice : Stone");
System.out.println("Draw!"); }
else if (rand==2){
System.out.println("User's Choice : Stone");
System.out.println("Opponent's Choice : Paper");
System.out.println("Opponent Wins!"); }
else if (rand ==3){
System.out.println("User's Choice : Stone");
System.out.println("Opponent's Choice : Scissor");
System.out.println("User Wins!"); }
break;
case "p":
if (rand==1){
System.out.println("User's Choice : Paper");
System.out.println("Opponent's Choice : Stone");
System.out.println("User Wins!");}
else if (rand ==2){
System.out.println("User's Choice : Paper");
System.out.println("Opponent's Choice : Paper");
System.out.println("Draw!");}
else if (rand == 3){
System.out.println("User's Choice : Paper");
System.out.println("Opponent's Choice : Scissor");
System.out.println("Opponent Wins!!");}
break;
case "sc":
if (rand==1){
System.out.println("User's Choice : Scissor");
System.out.println("Opponent's Choice : Stone");
System.out.println("Opponent Wins!!");}
else if (rand==2){
System.out.println("User's Choice : Scissor");
System.out.println("Opponent's Choice : Paper");
System.out.println("User Wins!");}
else if (rand==3){
System.out.println("User's Choice : Scissor");
System.out.println("Opponent's Choice : Scissor");
System.out.println("Draw!!");}
break;
}
System.out.println("--------------------------------------------------------------------------------------------------------------------");
System.out.println("Do you want to play again ? ");
System.out.println("Enter 'Y' for Yes and 'N' for No");
ans = in.nextLine();
}
while (ans =="Y");
}
}
答案 0 :(得分:0)
ans
才能处于循环条件的范围内。您还应该将字符串比较从==更改为等于。
String ans = "";
do {
String c;
...
} while (ans.equals("Y"));