【问题标题】:Boolean not inheriting [closed]布尔值不继承[关闭]
【发布时间】:2019-12-03 23:27:27
【问题描述】:

我在超类中创建了一个布尔方法,但是当我调用该方法在子类中使用它时,它给了我一个类型不匹配的错误,说它不能将布尔值转换为 A。我是可能遗漏了一些小东西,但是还有另一种方法可以在继承的类中使用该方法吗?

public class A{
    public boolean Proper(String expression){
    //body of method that determines if an expression is proper
    return true;
    }
}



public class B extends A {

    static BalancedExpressions Proper = new BalancedExpressions();

    public static void main(String[] args) {
                try {
                Scanner scanner = new Scanner(new File("src/Expressions.txt"));
                FileWriter output = new FileWriter(new File("Output.txt"));

                while (scanner.hasNextLine()) {
                    String nextLine = scanner.nextLine();

                    output.write(nextLine + "\t");

                    //following line is giving the error
                    if(Proper = true) {
                    output.write("proper" + "\n");
                    } else { 
                    output.write("improper" + "\n");
                }
                scanner.close();
                output.close();
                    }
            } 
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }


        }//end main

    }

【问题讨论】:

  • “错误说它不能将布尔值转换为 A”。我认为它抱怨它无法将其转换为 BalancedExpressions,但是,嘿,你能发布整个错误吗?
  • - 类型不匹配:无法从 BalancedExpressions 转换为布尔值 - 类型不匹配:无法从布尔值转换为

标签: java inheritance methods


【解决方案1】:

你必须写Proper("some string"),而不是Proper。如果你用括号写它,它是一个函数调用;如果你没有写它,那么它就是你的BalancedExpressions 变量。您还需要使用双等号==。您当前使用的行尝试将 true 分配给 Proper 成员变量。另外,你不需要写if (something == true),直接写if (something)

【讨论】:

    【解决方案2】:

    好吧,是的,你刚才打错了哈哈。

                    //Proper is already a boolean, so this would work perfectly,
    
                    if(Proper(nextLine)) {
                    output.write("proper" + "\n");
                    } else { 
                    output.write("improper" + "\n");
    

    您将正确设置为 true,而不是进行方法调用

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 2016-09-13
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多