[英]Read index and strings from text file Java
Suppose i have a text file that has a number code and a string label on each line:假设我有一个文本文件,每行都有一个数字代码和一个字符串 label:
0102 Apple Banana Code
0203 Pear Watch Time
0405 Java Computer Pen
0607 Car Bike Drive
How could i print the sum of the non zero numbers in the front and the first two words of each line?我如何打印前面非零数字的总和以及每行的前两个单词? Assuming that the numbers are always 4 digits and words are separated by a single space from the number and in between the words.假设数字始终是 4 位数字,并且单词与数字和单词之间由一个空格分隔。 For example I would get:例如我会得到:
3 Apple Banana
5 Pear Watch
9 Java Computer
13 Car Bike
I have tried to initialize this but i have no idea where to go from here我试图初始化它,但我不知道从这里到哪里去 go
FileReader fr = new FileReader(fileName);
BufferedReader inFile = new BufferedReader(fr);
String[][] words = new String[100][];
String line;
int size = 0;
while((line = inFile.readLine()) != null) {
words[size++] = line.split(" ");
}
inFile.close();
You are close.你很接近。 Refer to below code.参考下面的代码。 Explanations appear after the code.解释出现在代码之后。
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Tester {
private static void handleLine(String line) {
String[] parts = line.split(" ");
int num = handleNumber(parts[0]);
System.out.printf("%d %s %s%n", num, parts[1], parts[2]);
}
private static int handleNumber(String number) {
char[] digits = number.toCharArray();
int total = 0;
for (char digit : digits) {
total += digit - '0';
}
return total;
}
public static void main(String[] args) {
Path path = Path.of("tragedy.txt");
try (BufferedReader inFile = Files.newBufferedReader(path)) {
String line = inFile.readLine();
while (line != null) {
handleLine(line);
line = inFile.readLine();
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
BufferedReader
but it is not required.我使用 class Files创建BufferedReader
但这不是必需的。 Your code for obtaining a BufferedReader
is correct.您获取BufferedReader
的代码是正确的。char
is actually a number so to get the actual number value from the char
, I subtract the value of the 0
character. char
实际上是一个数字,因此要从char
中获取实际数值,我减去0
字符的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.