我需要编写一个程序,以双数组的形式读取和存储Java中的输入文件。文件中的值数存储在文件的第一行,然后是实际的数据值。
这是我到目前为止所做的:
public static void main(String[] args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("Please enter the name of the input file: ");
String inputFileName = console.next();
Scanner in = new Scanner(inputFileName);
int n = in.nextInt();
double[] array = new double[n];
for( int i = 0; i < array.length; i++)
{
array[i] = in.nextDouble();
}
console.close();
}
输入文件如下:
10
43628.45
36584.94
76583.47
36585.34
86736.45
46382.50
34853.02
46378.43
34759.42
37658.32
截至目前,无论我输入的文件名是什么,我都会收到一条异常消息:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Project6.main(Project.java:33)
答案 0 :(得分:8)
new Scanner(String)
构造函数扫描指定的String。不是字符串中路径名表示的文件。
如果要扫描文件,请使用
Scanner in = new Scanner(new File(inputFileName));
答案 1 :(得分:3)
检查以下代码。扫描程序必须与File
一起提供,而不仅仅是String
,如以下代码段所示:
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter the name of the input file: ");
String inputFileName = console.nextLine();
Scanner in = null;
try {
in = new Scanner(new File(inputFileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int n = in.nextInt();
double[] array = new double[n];
for (int i = 0; i < array.length; i++) {
array[i] = in.nextDouble();
}
for (double d : array) {
System.out.println(d);
}
console.close();
}
}
示例输出:
请输入输入文件的名称:c:/hadoop/sample.txt
43628.45
36584.94
76583.47
36585.34
86736.45
46382.5
34853.02
46378.43
34759.42
37658.32