2012-04-06 91 views
2
import java.io.*; 
    import java.util.*; 

    public class Readfilm { 

    public static void main(String[] args) throws IOException { 

     ArrayList films = new ArrayList(); 
     File file = new File("filmList.txt"); 
     try { 
      Scanner scanner = new Scanner(file); 

      while (scanner.hasNext()) 
      { 
       String filmName = scanner.next(); 
       System.out.println(filmName); 
      } 
     } 
     catch (FileNotFoundException e) 
     { 
      e.printStackTrace(); 
     } 
    }} 

以上是我目前正在嘗試使用的代碼,它編譯罰款,然後我得到的運行時錯誤:我GOOGLE了的Java從文件中讀取到陣列運行時錯誤

java.util.NoSuchElementException 
    at java.util.Scanner.throwFor(Scanner.java:907) 
    at java.util.Scanner.next(Scanner.java:1416) 
    at Readfilm.main(Readfilm.java:15) 

錯誤,沒有任何幫助(我只搜索錯誤的前3行)

基本上,我正在編寫的程序是更大程序的一部分。這部分是從哪個是這樣寫的文本文件獲取信息:

電影一個/ 1.5
電影二/ 1.3
電影三/ 2.1
電影四/ 4.0

與文本之中電影片名和浮動片是電影的持續時間(將會有20分鐘的時間添加到它(對於廣告),然後將四捨五入到最接近的整數)

繼續前進,程序然後把數組中的信息,因此可以訪問& modifie d很容易從程序中,然後寫回到文件中。

我的問題是:

我得到一個運行時錯誤目前,沒有線索如何解決? (目前我只是想讀取每一行,並將其存儲在一個數組中,作爲程序其餘部分的基礎)任何人都可以指向正確的方向嗎?

我不知道如何在「/」分裂我認爲這是像.split(「/」)?

任何幫助將不勝感激!

Zack。

+1

你的代碼適合我。我沒有'NoSuchElementException',我看不到你的代碼是如何生成的。 – 2012-04-06 07:17:51

回答

1

您的代碼工作,但它只是讀取一行。你可以在這裏使用的BufferedReader是一個例子

import java.io.*; 
class FileRead 
{ 
public static void main(String args[]) 
    { 
    try{ 
    // Open the file that is the first 
    // command line parameter 
    FileInputStream fstream = new FileInputStream("textfile.txt"); 
    // Get the object of DataInputStream 
    DataInputStream in = new DataInputStream(fstream); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
    String strLine; 
    //Read File Line By Line 
    while ((strLine = br.readLine()) != null) { 
    // Print the content on the console 
    System.out.println (strLine); 
    } 
    //Close the input stream 
    in.close(); 
    }catch (Exception e){//Catch exception if any 
    System.err.println("Error: " + e.getMessage()); 
    } 
    } 
}

這裏是一個分裂例如

class StringSplitExample { 
     public static void main(String[] args) { 
       String st = "Hello_World"; 
       String str[] = st.split("_"); 
       for (int i = 0; i < str.length; i++) { 
         System.out.println(str[i]); 
       } 
     } 
}

1

我不會用一個Scanner,那是符號化(你一次只能得到一個單詞或符號)。您可能只想使用BufferedReader,它有一個readLine方法,然後使用line.split("/"),因爲您建議將其分成兩部分。

0

懶惰溶液:

掃描儀掃描= ..;
scan.nextLine();