它指出我的“public station”构造方法有一个错误,它说我需要一个返回类型,但在我以前的代码中,我在尝试构造对象时从未遇到过这个问题。如果我使用 public void 那么我无法创建该对象,因为我的构造函数出了问题。
这是我使用“公共空站”的时候
public class StationReport{
//fields
/*# YOUR CODE HERE */
private String NAME;
private int yCoordinate;
private int xCoordinate;
private String dATE;
private int t;
private double temperature;
private double dewPoint;
private double pressure;
//Constructor
/*# YOUR CODE HERE */
public Station(String name, int x, int y, String date, int time, double temp, double dewpt, double press){
this.NAME = name;
this.xCoordinate = x;
this.yCoordinate = y;
this.dATE = date;
this.t = time;
this.temperature = temp;
this.dewPoint = dewpt;
this.pressure = press;
}
// Getter methods
/*# YOUR CODE HERE */
public String getName(){
return this.NAME;
}
public int getX(){
return this.xCoordinate;
}
public int getY(){
return this.yCoordinate;
}
public String getDate(){
return this.dATE;
}
public int getTime(){
return this.t;
}
public double getTemperature(){
return this.temperature;
}
public double getDewPoint(){
return this.dewPoint;
}
public double getPressure(){
return this.pressure;
}
// toString method
/** YOUR DOCUMENTATION COMMENT */
public String toString(){
/*# YOUR CODE HERE */
return NAME + ": " + xCoordinate + ": " + yCoordinate + ": " + dATE + ": " + t + ": " + temperature + ": " + dewPoint + ": " + pressure + ": ";
}
}
这是我尝试创建对象时的代码,但它说我的构造函数有问题。
/**
* Loads all the reports from the stations out of the file into
* the list of all reports.
*/
public void loadReports(){
this.allReports.clear();
try {
List<String> lines = Files.readAllLines(Path.of("reports.txt"));
for (String line: lines){
Scanner sc = new Scanner(line);
String name = sc.next();
int x = sc.nextInt();
int y = sc.nextInt();
String date = sc.next();
int time = sc.nextInt();
double temp = sc.nextDouble();
double dewpt = sc.nextDouble();
double press = sc.nextDouble();
StationReport report = new StationReport(name, x, y, date, time, temp, dewpt, press);
this.allReports.add(report);
}
UI.printf("Loaded %d reports.\n", allReports.size());
} catch(IOException e){UI.println("File reading failed");}
}
我尽了一切努力,但没有任何效果。
构造函数名称必须与类名称匹配,并且不能有返回类型。
Oracle 教程:构造函数
/*# YOUR CODE HERE */
public Station(String name, int x, int y, String date, int time, double temp, double dewpt, double press){
this.NAME = name;
this.xCoordinate = x;
this.yCoordinate = y;
this.dATE = date;
this.t = time;
this.temperature = temp;
this.dewPoint = dewpt;
this.pressure = press;
}
你的构造函数有一个错误 类名和构造函数名称始终应该匹配 这里将上面的方法名称替换为与类名称相同的名称即可工作