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 分钟(对于广告),然后将四舍五入到最接近的 int)
继续,程序然后将信息放在一个数组中,以便可以从程序轻松访问和修改它,然后写回文件。
我的问题是:
我目前遇到运行时错误,不知道如何解决?(目前我只是尝试读取每一行,并将其存储在数组中,作为程序其余部分的基础)谁能指出我正确的方向?
我不知道如何在"/"处进行拆分,我认为它类似于 .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();