簡體   English   中英

Java從文件讀取到數組運行時錯誤

[英]Java Read from file to Array runtime error

 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();
        }
    }}

上面是我目前嘗試使用的代碼,它編譯得很好,然后我得到一個運行時錯誤:

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 分鍾(對於廣告),然后將四舍五入到最接近的整數)

繼續,程序然后將信息放在一個數組中,以便可以從程序中輕松訪問和修改它,然后寫回文件。

我的問題是:

我目前收到一個運行時錯誤,不知道如何修復? (目前我只是想讀取每一行,並將其存儲在一個數組中,作為程序其余部分的基礎)有人能指出我正確的方向嗎?

我不知道如何在“/”處進行拆分,我認為它類似於 .split("/")?

任何幫助將不勝感激!

扎克。

您的代碼正在運行,但它只讀取一行。您可以使用 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]);
                }
        }
}

我不會使用Scanner ,那是為了標記化(一次只能得到一個詞或符號)。 您可能只想使用具有readLine方法的BufferedReader ,然后按照您的建議使用line.split("/")將其分成兩部分。

懶惰的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM