2012-10-02 68 views
0

我对Java还很陌生,我正在为类的项目工作,我不确定如何编写我的程序来获取userInput(fileName)并从中创建一个新对象。我的指令是编写一个程序,该程序从用户读取文件名,然后从该文件读取数据,创建对象(键入StudentInvoice)并将它们存储在ArrayList中。如何阅读用户输入以创建对象?

这就是我现在所处的位置。

public class StudentInvoiceListApp { 

    public static void main (String[] args) { 
    Scanner userInput = new Scanner(System.in); 
    String fileName; 

    System.out.println("Enter file name: "); 
    fileName = userInput.nextLine(); 

    ArrayList<StudentInvoice> invoiceList = new ArrayList<StudentInvoice>(); 
    invoiceList.add(new StudentInvoice()); 
    System.out.print(invoiceList + "\n"); 

    } 
+0

没有足够的信息来回答你的问题。例如,输入文件是什么样的?你可能会更好地问一个关于你卡在哪里的更具体的问题。 –

回答

0

您可以尝试写一个类串行化/从流反序列化对象(见this文章)。

0

那么,正如罗伯特所说,没有足够的关于存储在文件中的数据格式的信息。假设文件的每一行都包含学生的所有信息。您的程序将包括按行读取文件并为每行创建一个StudentInvoice。像这样:

public static void main(String args[]) throws Exception { 
    Scanner userInput = new Scanner(System.in); 
    List<StudentInvoice> studentInvoices = new ArrayList<StudentInvoice>(); 
    String line, filename; 

    do { 
     System.out.println("Enter data file: "); 
     filename = userInput.nextLine(); 
    } while (filename == null); 

    BufferedReader br = new BufferedReader(new FileReader(filename)); 
    while ((line = br.readLine()) != null) { 
     studentInvoices.add(new StudentInvoice(line)); 
    } 

    System.out.println("Total student invoices: " + studentInvoices.size()); 
}