我的程序显示错误“无法解析符号'getThePixels'”(在课程Main
中)。代码基本上创建了一个Monitor
类,其中包含Resolution
类的对象。我试图通过监视器对象访问Resolution
类方法。
以下是代码:
主:
public class Main {
Resolution resolution = new Resolution(10);
Monitor monitor = new Monitor(12,13,14,resolution);
monitor.getThePixels().pix();
}
显示器:
public class Monitor {
private int height;
private int width;
private int length;
Resolution thePixels;
public Monitor(int height, int width, int length, Resolution thePixels) {
this.height = height;
this.width = width;
this.length = length;
this.thePixels = thePixels;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public int getLength() {
return length;
}
public Resolution getThePixels() {
return thePixels;
}
}
分辨率:
public class Resolution {
private int pixels;
public Resolution(int pixels) {
this.pixels = pixels;
}
public void pix() {
System.out.println("resolution is" + pixels);
}
}
答案 0 :(得分:5)
你应该像这样编写你的Main类。
public class Main {
public static void main(String[] args) {
Resolution resolution = new Resolution(10);
Monitor monitor = new Monitor(12,13,14,resolution);
monitor.getThePixels().pix();
}
}
你不能在类体内的对象上调用方法。
答案 1 :(得分:3)
对getThePixels
的调用很好。但是,Java不允许在类的中间调用方法。这些类型的调用需要在方法,构造函数,匿名块或赋值中。
您似乎打算从main
方法调用这些行:
public class Main {
public static void main(String[] args) { // Here!
Resolution resolution = new Resolution(10);
Monitor monitor = new Monitor(12,13,14,resolution);
monitor.getThePixels().pix();
}
}
答案 2 :(得分:2)
public class Main {
Resolution resolution = new Resolution(10);
Monitor monitor = new Monitor(12,13,14,resolution);
monitor.getThePixels().pix();
}
这不会被运行,因为你没有main
方法来运行它:
我的意思是:
public static void main(String args[])
如果使用main
方法重写它,它可以工作:
public class Main {
public static void main(String args[]){
Resolution resolution = new Resolution(10);
Monitor monitor = new Monitor(12,13,14,resolution);
monitor.getThePixels().pix();
}
}