【问题标题】:(Java) Switch Cannot Find Symbol(Java) 开关找不到符号
【发布时间】:2016-03-03 00:17:00
【问题描述】:

cannot find symbol 使用开关时出现错误。但是,我之前做过切换,那是在驱动程序中。这是我第一次在自己的课堂上使用开关。无论如何,这里是我的代码示例:

import java.util.*;
public class TrumpWar
{

   protected CardPile pl;
   protected CardPile p2;
   protected CardPile tCard;
   protected CardPile treasury;

   public TrumpWar( )
   {
        CardPile cp = new CardPile (new Card [52]);
        cp.shuffle();

        CardPile tCard = new CardPile();
        for (int i=0; i<6; i++)
            tCard.get(i);
        cp.shuffle();

        CardPile p1 = new CardPile(new Card [26]);
        CardPile p2 = new CardPile(new Card [26]);
    }

public void play()
{
    Scanner kb = new Scanner(System.in);
    do
    {
        System.out.println("At each turn, type: ");
        System.out.println("P to print");
        System.out.println("M to mix (shuffle the cards)");
        System.out.println("S to save");
        System.out.println("Q to quit");
        System.out.println("just ENTER to play a turn");

        String meunChoice = kb.nextLine();

        if(!meunChoice.equals("M") || !meunChoice.equals("m") || !meunChoice.equals("P") || !meunChoice.equals("p") || !meunChoice.equals("Q") || !meunChoice.equals("q") || !meunChoice.equals("S") || !meunChoice.equals("s") || !meunChoice.equals(str = String.valueOf(kb.nextLine())))
            throw new IllegalArgumentException ("Incorrect input, please re-enter.");
        else
        {
            switch (meunChoice)
            {
                case ("P"):
                case ("p"):     System.out.println("Player1 cards: " + p1.toString()); //<--- Cannot find p1.
                                System.out.println("Player1 cards: " + p2.toString());
//More codes...

当我在 switch 范围之外明确声明 p1 时,我不知道为什么会出现该错误。除非,与驱动程序相比,在类中使用开关的方式不同。

另外,请忽略任何逻辑错误,因为这仍在进行中。我至少需要先编译程序,然后才能解决任何逻辑错误。

感谢您的帮助!

【问题讨论】:

  • 您可能想要重命名 CardPile pl;到 CardPile p1;并且不要在构造函数中重新声明它们。

标签: java class switch-statement


【解决方案1】:

属性名为pl不是p1,除了p1TrumpWar()构造函数中声明为局部变量,显然不能从@访问987654325@。你需要做的是:

// outside

protected CardPile p1; // you wrote pl, rename it!

// in the constructor

p1 = new CardPile(new Card [26]);
p2 = new CardPile(new Card [26]);

现在属性 p1p2 正在被实例化,在您的代码中,您声明了几个恰好与属性具有(几乎)同名的局部变量 - a编译器警告应该告诉你。

【讨论】:

  • 并将类顶部的pl重命名为p1。
【解决方案2】:

问题似乎是您在构造函数中重新声明 p1 和 p2 变量。

代替

 CardPile p1 = new CardPile(new Card [26]);
 CardPile p2 = new CardPile(new Card [26]);

尝试做

 p1 = new CardPile(new Card [26]);
 p2 = new CardPile(new Card [26]);

不同之处在于,在第一种情况下,您声明了一个变量(因为它具有类类型,即 CardPile),而在第二种情况下,您使用的是已经在顶部声明的变量,这就是您想要做的显然。

因此,如果您在构造函数中重新定义变量 p1 和 p2,它们将在其外部保持未定义,即在 play() 内部 p1 和 p2 为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多