因此,我正在创建一个日志记录程序,用户可以在其中输入KM并将其保存等。
我输入四个变量-开始KM,结束KM,开始和结束位置。我是java的新手,所以我只是想知道是否有人可以确认是否有更好的方法来做到这一点。到目前为止,这是我的代码,我想将其保存到各种数组(到列表中?),以便可以访问每个对象(即startKM),但它们必须位于同一行,如数组的对象1中那样等等,然后写入文件,
我当时想做的就是将链接列表保存到文件中,并添加一个;在toString方法中,并且在读取文件时只是在处将其断开;有一个更好的方法吗??谢谢你们。数据是根据用户在文本字段中输入的内容分配的。
double startKM;
double endKM;
String startLocation;
String endLocation;
startKM = Double.parseDouble(txtStartKM.getText());
endKM = Double.parseDouble(txtEndKM.getText());
startLocation = txtStartLocation.getText();
endLocation = txtEndLocation.getText();
details.startKM = startKM;
details.endKM = endKM;
details.startLocation = startLocation;
details.endLocation = endLocation;
//List<DrivingDetails> detailsList = new ArrayList<DrivingDetails>();
List detailsList = new ArrayList();
detailsList.add(details);
System.out.println("LinkedList contains = \t " + detailsList.toString());
编辑:我有另一个类(DrivingDetails),其中包含以下变量:
public class DrivingDetails {
double startKM;
double endKM;
String startLocation;
String endLocation;
}
您的DrivingDetails类违反了面向对象类的封装原理。我会为所有属性添加setter和getter。另外,您可以创建一个为您处理初始化的构造函数。
public class DrivingDetails {
private double startKM;
private double endKM;
private String startLocation;
private String endLocation;
public DrivingDetails(double startKM, double endKM, String startLocation, String endLocation) {
this.startKM = startKM;
this.endKM = endKM;
this.startLocation = startLocation;
this.endLocation = endLocation;
}
public double getStartKM() {
return startKM;
}
public void setStartKM(double startKM) {
this.startKM = startKM;
}
// rest of the methods left for you ...
}
结果代码如下:
double startKM;
double endKM;
try {
startKM = Double.parseDouble(txtStartKM.getText());
endKM = Double.parseDouble(txtEndKM.getText());
} catch (NumberFormatException e | NullPointerException e) {
// the line above assumes java 7
// recover
}
DrivingDetails details = new DrivingDetails(startKM, endKM,
txtStartLocation.getText(),
txtEndLocation.getText());
List<DrivingDetails> detailsList = new ArrayList<DrivingDetails>();
detailsList.add(details);
希望对您有所帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句