2013-11-21 76 views
0

我完全失去了在數組和需要幫助之中......這是這一計劃的最終目標....請幫幫忙,FileNotFound異常等prblems

在一個名爲AccountArray.java文件,寫客戶端程序(您的主要方法)從名爲customers.txt的文件中讀取。閱讀文件中的第一個數字,並使用該數量的元素創建一個Account對象數組。使用「for」循環爲從文件中讀取的每一行信息創建一個Account對象,並將其存儲到數組的元素中

這裏是我到目前爲止的地方......我主要關心的是FileNotFound異常錯誤....我有一個名爲customers.txt文件保存在程序文件夾中,但我需要初始化它莫名其妙?

關於我在這個程序中做錯的事情,任何其他輸入都會被大大接受,我剛剛開始學習這些東西。

public class AccountArray { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 



      List<Account> accountsArray = new ArrayList <Account>(); 


      String name, accountnumber, balance; 

      Scanner diskScanner = new Scanner(new File("customers.txt")); 
      Scanner scanner= new Scanner ("customers.txt"); 
      scanner.useDelimiter(" "); 
      int objects= scanner.nextInt(); 
      Account[] accounts=new Account[objects]; 

      while (objects>0){ 
       name = scanner.nextLine(); 
       accountnumber = scanner.nextLine(); 
       balance = scanner.nextLine(); 


        for(int i = 1; i < objects; i++) { 
         accountsArray.add(new Account(i, name, accountnumber, balance)); 
        } 

        objects=objects-1; 


        System.out.println(name+ " " + accountnumber + " " + balance +"\n"); }// just for debugging 


} 

}

示例文件:

4 
John Anderson 
4565413 
250.00 
Louise Carter 
2323472 
1250.45 
Paul Johnson 
7267881 
942.81 
Sarah Wilson 
0982377 
311.26 
+0

如果是相對於「保存在程序文件夾」到你的java編譯課是? .txt文件需要位於同一個目錄中。 – OldProgrammer

+0

真的很新鮮,不太清楚目錄是什麼....我有一個名爲AccountArray的程序,帶有3個類和文件 – user2954611

+0

@ user2954611你知道什麼是「相對」和「絕對」路徑嗎? – Smit

回答

0

這是運行形式蝕。如果是,你需要在你的項目根文件夾下有這個文件。你總是可以通過使用

new File("customers.txt").getAbsoultePath(); 

打印到控制檯,看看文件存在於這個位置

+0

所以我有位置.... C:\ Users \ shc115 \ workspace \ AccountArray \ customers.txt但我如何讓它讀取此 – user2954611

1

那麼,首先找出絕對路徑,你用錯了對象Scanner

Scanner diskScanner = new Scanner(new File("customers.txt")); // Scans through your file --Use this one 
Scanner scanner= new Scanner ("customers.txt"); // Scans through the String "customers.txt" --Not helpful 

要解決的FileNotFound例外,您需要將文件Customers.txt移動移動到由new File("customers.txt").getAbsoultePath();輸出由辣媽Thommi所建議的文件夾。

你還會遇到一些其他錯誤進一步下跌,但我會讓你弄清楚那些在你自己......