更改if切换语句

时间:2018-05-11 18:44:45

标签: java

我正在为我的java课程的Treasure Hunt游戏项目工作,当教授要求我这样做时,我感到非常困惑"不要使用instanceof或者break,除了在switch语句中。 #34; 目前在我正在使用if和for语句的函数内部。 我可以改变它,这样我可以摆脱咒语吗?

在按钮部分我正在使用if(...。intanceof ...) 我能尝试和捕获吗?而不是如果?如果是这样的话?

宝藏游戏

 import java.awt.*;
import java.util.Random;
import javax.swing.*;

public class TreasureBoardPanel extends JPanel 
{
    private static final int WIDTH = 10;
    private static final int HEIGHT = 10;

    // Instance variables
    private BoardButton[] button;   //used to add the button to the panel
    private TreasureGame game;      //used to make make the constructor for the TreasureBoardPanel

    //Costructor
    public TreasureBoardPanel(TreasureGame game) 
    {
        super();
        this.game = game;
        //setting the layout
        setLayout(new GridLayout(WIDTH, HEIGHT));
        //adding the buttons
        addButtons();
    }

    //Create and adding buttons to panel
    private void addButtons() 
    {
        this.button = new BoardButton[WIDTH * HEIGHT];

        //creating the random buttons
        Random random = new Random();

        for (int i = 0; i < TreasureGame.NUM_TREASURES; i++) 
        {
            int index = random.nextInt(this.button.length);
            //Check if index is already a button
            while (this.button[index] != null)
                index = random.nextInt(this.button.length);
            this.button[index] = new TreasureButton();
        }

        // For all the buttons which are not TreasureButton i.e. null buttons
        // create BoardButton
        for (int i = 0; i < this.button.length; i++) 
        {
            if (this.button[i] == null)
                this.button[i] = new BoardButton();
        }

        // Add all buttons to the panel and add action listener
        for (int i = 0; i < this.button.length; i++) 
        {
            this.button[i].addActionListener(new ButtonListener(game));
            add(this.button[i]);
        }
    }

    //Display text from all treasures method
    public void displayAllTreasures() 
    {
        for (int i = 0; i < this.button.length; i++) 
        {
            if (this.button[i] instanceof TreasureButton)

                this.button[i].setText(this.button[i].getDisplayText());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的教授所提出的观点并非用if替换switch,而是为了避免首先使用instanceofuse polymorphism instead。通常,您只需向对象的类添加一个方法,该方法可以处理任务本身或返回任务所需的信息,并在子类中覆盖它。

在这种情况下,您可以向名为BoardButton的{​​{1}}添加一个返回isTreasure的方法,并false覆盖它以返回TreasureButton。然后你可以调用true而不是检查它是哪个类。