从数据文件中读取来填充的ArrayList [英] Reading from data file to fill ArrayList
问题描述
我有一个抽象类,订单有三个不同的类实现它一切都在程序运行正常,当我硬codeD命令测试它的程序。
I have a program with an abstract class 'Orders' with three different classes implementing it everything in the program runs fine when I tested it with hard coded orders.
下面是抽象类:
public abstract class Order {
protected String location;
protected double price;
public Order(double price, String location){
this.price = price;
this.location = location;
}
public abstract double calculateBill();
public String getLocation() {
return location;
}
public double getPrice() {
return price;
}
public abstract String printOrder(String format);
}
在这里参考实施的一个类
And here is one of the implementing classes for reference
public class NonProfitOrder extends Order {
public NonProfitOrder(double price, String location) {
super(price, location);
}
public double calculateBill() {
return getPrice();
}
public String printOrder(String format){
String Long = "Non-Profit Order" + "\nLocation: " + getLocation() + "\nTotal Price: " + getPrice();
String Short = "Non-Profit Order-Location: " + getLocation() + ", " + "Total Price: " + getPrice();
if (format.equals("Long")){
return Long;
}
else{
return Short;
}
}
}
这是我的测试,到目前为止,我知道这是错的,pretty凌乱,但处之泰然。 Iv'e一直乱搞努力得到的东西的工作,但没有运气。
This is what I have for a tester so far, I know it is wrong and pretty messy, but take it easy. Iv'e been messing around trying to get something to work, but no luck.
public static ArrayList<Order> readOrders (String fileName) throws FileNotFoundException{
String type;
Scanner s = new Scanner(new File("orders.txt"));
ArrayList<Order> orders = new ArrayList<Order>();
while (s.hasNext()){
type = s.nextLine();
}
switch(type) {
case 1: type = NonProfitOrder();
break;
case 2: type = RegularOrder();
break;
case 3: type = OverseasOrder();
return orders;
}
}
数据文件,我需要从这个样子的阅读:
The data file I need to read from looks like this:
N 1000.0 NY
R 2000.0 CA 0.09
R 500.0 GA 0.07
N 2000.0 WY
O 3000.0 Japan 0.11 20.0
N 555.50 CA
O 3300.0 Ecuador 0.03 30.0
R 600.0 NC 0.06
首先我无法读取该文件,我知道我需要一个循环,将数据添加到ArrayList,但我不知道怎么样。什么是一个方法来读取和环路所有的最简单的方法?如果可能的话。
First off I am having trouble reading the file, I know i need a loop to add the data to the arrayList, but I'm not sure how . What would be the easiest way to read and loop all in one method? If possible.
我更新了几分添加一个switch语句,我有,不工作的。相反情况下,1,2,3,你会不会反而需要使用一些与N,O,R投其所好与文件
而我无法修复错误类型不匹配。
I updated to add the somewhat of a switch statement that I have, that doesn't work. Instead of case 1,2,3, would I instead need to use something with N, O, R to match up with the file and I'm having trouble fixing the error "type mismatch".
推荐答案
的扫描仪提供了一种简便的方式,通过文件来走。 。接下来().hasNext().nextLine().hasNextLine()是你的情况是非常有用的方法。
Scanner provides an easy way to walk through the file. .next() .hasNext() .nextLine() .hasNextLine() are very useful methods in your case.
这篇关于从数据文件中读取来填充的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!