java – 以双数组的形式读取和存储文件内容
发布时间:2020-12-14 05:43:09 所属栏目:Java 来源:网络整理
导读:我需要编写一个程序,用 Java中的双数组读取和存储输入的文件.文件中的值数存储在文件的第一行,然后是实际数据值. 这是我到目前为止: public static void main(String[] args) throws FileNotFoundException{ Scanner console = new Scanner(System.in); Sys
我需要编写一个程序,用
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(); } 输入文件如下:
截至目前,无论我输入的文件名是什么,我都收到一条异常消息: 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) 解决方法
请检查以下代码.扫描程序必须提供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(); } } 样本输出:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |