Reading and saving file contents in a double array

I need to write a program that reads and saves the entered file in Java in a double array. The number of values ​​in the file is stored in the first line of the file, then the actual data values ​​follow.

Here is what I still have:

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

The input file is as follows:

ten
43628.45
36584.94
76583.47
36585.34
86736.45
46382.50
34853.02
46378.43
34759.42
37,658.32

At the moment, regardless of the file name I entered, I get an error message:

 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) 
+6
source share
2 answers

Check out the following code. The scanner should have File instead of String , as shown in the following snippet:

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

Output Example:

Enter the name of the input file: c: /hadoop/sample.txt
43628.45
36584.94
76583.47
36585.34
86736.45
46382.5
34853.02
46378.43
34759.42
37,658.32

+3
source

new Scanner(String) constructor scans the specified string. Not the file indicated by the path name in the line.

If you want to scan a file, use

 Scanner in = new Scanner(new File(inputFileName)); 
+8
source

Source: https://habr.com/ru/post/989876/


All Articles