简体   繁体   English

为什么我不能在这个循环中调用另一个类的方法?

[英]Why can't I call a method from another class in this loop?

I'm trying to make a filter in the Catalogue class that will later print out 'parts' that have a price greater than the minimum price that the user has entered.我正在尝试在 Catalog 类中创建一个过滤器,稍后将打印出价格高于用户输入的最低价格的“零件”。 However I am not able to call getNumPrice() (which is in the Part class) from the Catalogue class and I am not sure why?但是,我无法从 Catalog 类调用 getNumPrice()(在 Part 类中),我不确定为什么? How can I fix this and what am I doing wrong?我该如何解决这个问题,我做错了什么?

   //The following is in the Part class

 public double getNumPrice(){
        return this.price;
    }

//The following is in the Catalogue class

 private double readMinPrice(){
        System.out.println("Enter minimum price ('-1' for no filtering): ");
        return In.nextDouble();
    }

 private void filter(){
        String type =readTypeFilter();
        double minPrice = readMinPrice();

       if ( type== "all" && minPrice==-1)
            showParts();
        else if (type=="all" && minPrice >= 0)

            for(int i=0; i<= parts.size();i++)
                if (part.getNumPrice() >= minPrice)
                    System.out.println( i+1 + "." +  parts.get(i));
}

You have a parts collection and you are calling part.getNumPrice() in your loop.您有一个parts集合,并且正在循环中调用part.getNumPrice()

I don't see either declared in your code but I'm assuming parts is a field and you are trying to do something like parts.get(i).getNumPrice() in the loop.我在您的代码中没有看到任何声明,但我假设parts是一个字段,并且您正在尝试在循环中执行parts.get(i).getNumPrice()之类的操作。

You need to use the indexed part in your loop.您需要在循环中使用索引部分。

for(int i=0; i<= parts.size();i++)
   if (parts.get(i).getNumPrice() >= minPrice)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么不能从Java中另一个包的继承类调用受保护的方法? - Why can't I call a protected method from an inheriting class in another package in Java? 无法从其他类调用方法 - Can't call method from another class 为什么我不能从另一个 class 访问此方法? - Why can't I access this method from another class? 为什么我不能从另一个类访问方法 - why i can't access to method from another class 为什么不能在同一个包中调用另一个类的包私有方法呢? - Why can't I call a package-private method of another class that's a subclass of a class in the same package? 在另一个函数中创建子类的实例时,为什么不能从子类类型的 Abstact 类调用方法(公共或静态)? - Why can't I call a method (public or static) from an Abstact class of type subclass when creating an instance of the subclass in another function? 无法从另一个类到主类调用静态方法 - Can't call a static method from another class to main class 为什么我不能在主类中使用main方法创建另一种方法? - why can't I create another method aside from main method in main class? 无法从另一个类JAVA调用方法 - Can't call a method from another class JAVA 无法从 Java 中的另一个类调用方法 - Can't call method from another class in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM