0

我正在尝试用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) ,但也没有用。

4

2 回答 2

2

您要么需要在ch上方声明switch (c),要么ch在每个case开关中声明。

而且由于您似乎想ch在以后使用,因此您需要以下代码段:

char ch = '\u0000';
switch (c)
{
  case 1: 
    String choice = "r";
    ch = choice.charAt(0);
    break;
  case 2:
    String choice = "p";
    ch = choice.charAt(0);
    break;
  case 3:
    String choice = "s";
    ch = choice.charAt(0);
    break;

char ch注意顶部的声明 ( ),在cases 中只有赋值。

更新:同样适用于String choice,但是对于这个来说,似乎最好在每个case.

很多代码可以改进,但我只是在这里回答你的问题,例如你可以只输入ch = 'r'而不是String choice = "r"; ch = choice.charAt(0);

于 2013-12-08T21:20:44.467 回答
1

When declaring char "ch" in the case of a switch statement, it can only be used for that case with that switch statement, in order to fix this you must declare:

char ch;

outside of the switch; right after the declaration of string pc.

I suggest using an IDE to further help you if you, an IDE will automatically pick this up and tell you to correct the error.

于 2013-12-08T21:22:22.297 回答