java - 如何使用instanceof函数打印继承中的某个类别?

标签 java oop inheritance instanceof

我的三个子类(class)是脱口秀、歌曲和广播类(class)的广告。我这里只播放脱口秀节目。例如,当我输入 s、p 或 m 作为子类别时。当我只想打印一个子类别时,它会打印该子类的所有内容。

示例数据如下。

1000,S,The Newest Star,Space,51:20,T2.mp3
1001,P,Interview With George,Politics,15:00,george.mp3
1002,P,Crooks in Politics,Politics,21:35,crooks.mp3
1010,M,Cooking For Vegetarians,Food,5:00,vege2.mp3
1222,S,Where Is The Sun,Larries,23:33,larscience.mp3

但是如果我选择“P”作为脱口秀的子类别,它应该只打印这两个,如下所示。

1001,P,Interview With George,Politics,15:00,george.mp3
1002,P,Crooks in Politics,Politics,21:35,crooks.mp3

这是我的代码的一部分

private void searchCategoryToPrint() 
    {
        String inputCategory = JOptionPane.showInputDialog("Choose from Radio Categories: Talk Show, Song, or Commercial\n" +
                                                           "and enter the chosen category");
        String subCategory = JOptionPane.showInputDialog("Talk Show: S Science, P Politics, and M Miscellaneous\n");
        if("talk show".equalsIgnoreCase(inputCategory))
        {
                for(Radio radioShows : radioList)
                {
                    if("SPM".contains(subCategory.toUpperCase().substring(0)) && radioShows instanceof TalkShow)
                    {
                        System.out.println(radioShows.formatForFile());
                    }
                }
        }

最佳答案

您应该更改 if 条件来检查广播节目是否与从对话框中选择的子类别具有相同的子类别:

if(radioShows.getCategory().equalsIgnoreCase(subCategory.substring(0)) && radioShows instanceof TalkShow) {
    System.out.println(radioShows.formatForFile());
}

关于java - 如何使用instanceof函数打印继承中的某个类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42192989/

相关文章:

java - EntityManager.merge 没有做任何事情

Java 基本类型 XML 文本值

C# 从类中获取值到 mainForm

javascript - 为什么要在函数及其原型(prototype)上都设置一个属性?

python - 测试调用重写方法的类中的方法

java - 缺乏多重继承的解决方法

java - 我该如何识别按钮?

java - setFlags 后工具栏与状态栏重叠

c++ - C++代码错误

c++ - 在子类中重写时如何调用私有(private)虚拟基类实现