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)宣言する必要があります。chcase

そして、後で使用したいと思われるので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) が上部にあることに注意してください。scaseには代入だけがあります。

更新:同じことが にも当てはまりますString choiceが、これについては、 every で宣言する方がよいよう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 に答える