我正在尝试从包含以下格式编写的信息的文件中读取: someName:aDoubleNumber 并返回名称和双精度数。 我写了下面的扫描仪,但它没有用,有什么想法吗?
Scanner readFile = new Scanner("text.txt");
readFile.useDelimiter(":");
while (fileScanner.hasNext()) {
String name = readFile.next();
}
答案 0 :(得分:7)
你不是在读文件。你正在读字符串“text.txt”。你首先需要一个文件。
Scanner readFile = new Scanner(new File("text.txt")); // don't forget to catch FileNotFoundException!
readFile.useDelimiter(":|\\n");
while (fileScanner.hasNext()) {
String name = readFile.next();
double value = readFile.nextDouble();
System.out.println(name + " " + value);
}
我从您的评论中获取了代码并进行了格式化,我得到了这个
public class MyProject {
class FileInput {
Scanner readFile = new Scanner(new File("text.txt")); // don't forget to catch FileNotFoundException!
readFile.useDelimiter(":|\\n");
while (fileScanner.hasNext()) {
String name = readFile.next();
double value = readFile.nextDouble();
System.out.println(name + " " + value);
}
}
}
现在你似乎遇到了问题 - 也许你的意思是class FileInput
是public void fileInput() throws Exception
?当我这样做时,它会编译。现在我们需要一个main()
方法来运行它!所以我补充一点:
public static void main(String[] args) throws Exception {
MyProject proj = new MyProject();
proj.fileInput();
}
现在,当我运行它时,我确实遇到了错误。这意味着我给你开始的代码实际上存在问题。当然,该代码从未打算复制/粘贴,但更多的是提供功能的概念。无论如何,错误是:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at MyProject.fileInput(MyProject.java:9) <--- Where it happened in our code
at MyProject.main(MyProject.java:16)
它发生的行在parseDouble上。所以,相反,让我们尝试以不同的方式。我们可以将double作为原始文本,然后将其解析为一个实际的双重文本:
while (readFile.hasNext()) {
String name = readFile.next();
String valueStr = readFile.next();
double value = Double.parseDouble(valueStr);
System.out.println(name + " " + value);
}
所以整个完成的程序是:
import java.util.*;
import java.io.*;
public class MyProject {
public void fileInput() throws Exception {
Scanner readFile = new Scanner(new File("text.txt")); // don't forget to catch FileNotFoundException!
readFile.useDelimiter(":|\\n");
while (readFile.hasNext()) {
String name = readFile.next();
String valueStr = readFile.next();
double value = Double.parseDouble(valueStr);
System.out.println("Name: " + name);
System.out.println("Value: " + value);
System.out.println(""); // blank line
}
}
public static void main(String[] args) throws Exception {
MyProject proj = new MyProject();
proj.fileInput();
}
因此输入文件文本为:
this:1234.5
that:321.0
the other:0.122
输出
C:\Documents and Settings\glowcoder\My Documents>java MyProject
Name: this
Value: 1234.5
Name: that
Value: 321.0
Name: the other
Value: 0.122
C:\Documents and Settings\glowcoder\My Documents>java MyProject
}