For my question I saw an reminder that many have already asked this question, but I cant seem to find a decent answer. Or answers are in other programing languages which doesnt help me. So I will ask again :)
I have to read from a txt file, then do some mathematical operations on the data. This data is in 10000 lines and in each line is 20 numbers separated by a semicolon. For reading from txt file I used BufferedReader which gives me string. I probably have to change this string to int. So far so good. Then I have to make it into an array...how? Does the array need to be two dimensional or one dimension is enough?
Then in the end I have to write results in different txt files. I have to write to different files numbers that are dividable by 3, 11 and 5, then I have to sum each row in txt file and make the sum of whole txt numbers. Is what I wrote until now ok? Should I delete something or?
class Assignment {
public static void main (String[] args) {
String nameFile = "numbers.txt";
String contentFile = readFromFile(nameFile);
List<Integer> divideNumber = stringToIntList(contentFile);
List<Integer> divisibleNo = processedData(divideNumber);
System.out.println(divideNumber);
}
private static String readFromFile(String nameFile) {
String content = "";
try {
File file = new File(nameFile);
BufferedReader read = new BufferedReader(new FileReader(file));
String line = read.readLine();
while(line != null) {
System.out.println(line);
line = read.readLine();
content = line;
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from the file");
}
return content;
}
private static List<Integer> stringToIntList(String contentFile) {
return Arrays
.stream(contentFile.split("; "))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
private static int processedData(int divideNumber) {
try {
for(int i = 0; i < divideNumber; i++) {
if((divideNumber % 3 == 0) || (divideNumber % 5 == 0) || (divideNumber % 11 == 0)) {
System.out.println(divideNumber);
}
}
}
catch(NumberFormatException e){
System.out.println("It is not a number");
}
return divideNumber;
}
}
Use a Scanner with appropriate delimiter:
List<Integer> list = new ArrayList<>();
Scanner scanner = new Scanner(new FileInputStream(nameFile))
.useDelimiter("\\D+");
while (scanner.hasNext()) {
int i = scanner.nextInt();
list.add(i);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.