Answer the question
In order to leave comments, you need to log in
How to correctly read numbers from a file in java?
Wrote a method that should read 150 numbers from a file and place them in an array.
package com.keller;
import java.util.*;
import java.io.*;
public class MyCalc {
public static void main(String[] args) {
MyCalc cal = new MyCalc();
File file = new File("input.txt");
int[] A = cal.getData(file);
}
public int[] getData(File file) throws FileNotFoundException {
Scanner scan = new Scanner(file);
int[] dataArray = new int[150];
int i = 0;
while(scan.hasNextInt()) {
dataArray[i] = scan.nextInt();
i++;
}
return dataArray;
}
}
Answer the question
In order to leave comments, you need to log in
$ cat com/keller/MyCalc.java
package com.keller;
import java.util.*;
import java.io.*;
public class MyCalc {
public static void main(String[] args) throws IOException {
MyCalc cal = new MyCalc();
File file = new File("input.txt");
int[] A = cal.getData(file);
}
public int[] getData(File file) throws FileNotFoundException {
Scanner scan = new Scanner(file);
int[] dataArray = new int[150];
int i = 0;
while(scan.hasNextInt()) {
dataArray[i] = scan.nextInt();
i++;
}
return dataArray;
}
}
$ javac com/keller/MyCalc.java
$ java com/keller/MyCalc
I already determine the author by the style of the questions. Stop posting puzzles, solve for yourself.
In fact, the answer has already been given, but I advise you not to use the scanner, except perhaps only for a small amount of data (tests). Its performance makes me very unhappy. For example, here is an example with a click
buff reader
. And if there is a certain structure, then it is best to use stringtokenizer, this is something similar to stringstreamera in c ++
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question