這是我的代碼,它接受一個文本文件並創建一個Account對象,我遇到了麻煩與被打印出來是賬戶的銀行數組中的帳戶對象使用輸入文件來創建一個對象,並將該對象添加到一個數組,並讓它打印出該數組上的信息
public static void main (String[] args)
{
try {
// Read data from a file into a Bank.
// Each line of the file has info for one account.
BankInterface myBank = readFromFile("BankAccounts.txt");
// Print all the data stored in the bank.
System.out.println (myBank);
} // end try
catch (IOException ioe) {
System.out.println("IOException in main: " + ioe.getMessage());
ioe.printStackTrace();
} // end catch
catch (Exception e) {
System.out.println("Exception in main: " + e.getMessage());
e.printStackTrace();
} // end catch
} // end main
/**
* readFromFile: **** INSERT COMMENTS ****
*
*/
public static BankInterface readFromFile (String fileName) throws IOException
{
// Creata a bank.
BankInterface myBank = new Bank("Bank");
// Open a file for reading.
Scanner inputSource = new Scanner (new File(fileName));
// while there are more tokens to read from the input source...
while (inputSource.hasNext()) {
// Read one line of input from the file into an Account object
Account acct = InputManager.readOneAccountFrom (inputSource);
// Store the account info in the bank.
//**** INSERT CODE TO ADD acct TO THE BANK ****
myBank.addAccount(acct);
} // end while
return myBank;
} // end readFromFile
當我運行,我沒有得到帳戶打印出主我只是得到:
Reading: name,id,balance
Exception in main: null
可有人解釋爲什麼會發生這種情況,以及如何解決它? 堆棧跟蹤:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at InputManager.readOneAccountFrom(InputManager.java:30)
at ATM.readFromFile(ATM.java:48)
at ATM.main(ATM.java:15)
at __SHELL3.run(__SHELL3.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at bluej.runtime.ExecServer$3.run(ExecServer.java:730)
這裏是readOneAccountFrom方法:
什麼是堆棧跟蹤? –
爲了便於調試,禁用不需要的catch塊,例如那些處理未經檢查的異常的塊。第二個catch塊中的代碼浪費了調試所需的重要上下文信息。 – 2016-05-12 21:27:55
問題出在''''''''readOneAccountFrom'''方法中,你從掃描儀獲取信息,但它沒有任何信息。 [文檔](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNext--)表示何時拋出此類異常。 –