[英]How to read a text file in Java and split it?
I need help with writting a program, which will read me a file in Java and then split the words and will count the average of notes.我在编写一个程序时需要帮助,它会用 Java 读一个文件,然后拆分单词并计算音符的平均值。 So I have a file in Java called dziennik.txt and there in two lines I have a name, surname, the number of notes and then the notes of a student.
所以我在 Java 中有一个名为 dziennik.txt 的文件,在两行中我有名字、姓氏、笔记数量,然后是学生的笔记。 It looks like this:
它看起来像这样:
Mark Stank 3 4 5 6马克斯坦克 3 4 5 6
Veronica Lee 2 2 4维罗妮卡·李 2 2 4
So what I need to do is split words so that program will know that the 3 word is a number of notes and the next ones are these notes and it will count the average.所以我需要做的是拆分单词,这样程序就会知道第 3 个单词是一些音符,接下来的是这些音符,它会计算平均值。 For now I have sth like this:
现在我有这样的东西:
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class FileWrite {
public static void main(String[] args) throws IOException {
StringBuilder dziennik = new StringBuilder();
try (BufferedReader br = Files.newBufferedReader(Paths.get("dziennik.txt"))) {
// read line by line
String line;
while ((line = br.readLine()) != null) {
dziennik.append(line).append("\n");
String[] pair = line.split(" ");
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
System.out.println(dziennik);
}
}
I am new to this, so please explain this to me as simple as it can be.我对此很陌生,所以请尽可能简单地向我解释一下。
Similar to what spork mentioned.类似于spork提到的。 Here's a way to get the average number of notes per student:
这是获取每个学生的平均笔记数的方法:
StringBuilder dziennik = new StringBuilder();
double total = 0; // Added line
double counter = 0; // Added line
try (BufferedReader br = Files.newBufferedReader(Paths.get("dziennik.txt"))) {
// read line by line
String line;
while ((line = br.readLine()) != null) {
dziennik.append(line).append("\n");
String[] pair = line.split(" ");
total = total + Double.valueOf(pair[2]); // Added line
counter++; // Added line
}
System.out.println("Average number of notes per student: " + total / counter); // Added line
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
System.out.println(dziennik);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.