我需要解析多个文件并且在对象初始化外部访问对象方法。以下是我的代码:
public static void main(String[] args) {
try {
File Attrationfile = new File("attractions.txt");
Scanner attractionscanner = null;
attractionscanner = new Scanner(Attrationfile);
while (attractionscanner.hasNext()) {
String nextline = attractionscanner.nextLine();
String[] Attractioncomponents = nextline.split("@");
String ridename =Attractioncomponents[0];
int price = Integer.parseInt(Attractioncomponents[1]);
String type = Attractioncomponents[2];
int unknown = Integer.parseInt(Attractioncomponents[3]) ;
double speed = Attractioncomponents.length <= 4 ? 0 :
Double.parseDouble(Attractioncomponents[4]);
RollerCoaster rollerCoaster = new RollerCoaster(ridename, price , unknown, speed);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
File Customerfile = new File("customers.txt");
Scanner Customerscanner = new Scanner(Customerfile);
while (Customerscanner.hasNext()) {
String nextline = Customerscanner.nextLine();
String[] Customercomponents = nextline.split("#");
int accountnumber =Integer.parseInt(Customercomponents[0]);
String name = Customercomponents[1];
int age = Integer.parseInt(Customercomponents[2]) ;
int balance = Integer.parseInt(Customercomponents[3]) ;
String discount = Customercomponents.length <= 4
? String.valueOf(0) : Customercomponents[4];
Customer customer= new Customer(accountnumber,name, age, balance, discount);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
这个代码可以运行,但是我无法在它们的循环之外访问对象。我不确定如何使“顾客”类获取有关过山车的信息,例如名称和价格。例如,如果顾客和过山车对象在同一区域,那么我就能通过从
rollercoaster.getprice
减去customer.getbalance
来更新顾客余额,并将customer.setbalance
设置为计算值。正如你可能已经了解到的那样,我是一个初学者,所以我可能走了错误的路 - 谢谢。