[英]how do i detect a double line break in a data file
I have a data file that consists of a calorie count.我有一个包含卡路里计数的数据文件。 the calorie count it separated by each elf that owns it and how many calories are in each fruit.
卡路里计数由拥有它的每个精灵分开,以及每个水果中有多少卡路里。 so this represents 3 elves
所以这代表了 3 个精灵
4323
4004
4070
1780
5899
1912
2796
5743
3008
1703
4870
5048
2485
1204
30180
33734
19662
all the numbers next to each other are the same elf.所有相邻的数字都是同一个精灵。 the separated ones are seperate.
分开的是分开的。
i tried to detect the double line break like so我试图像这样检测双线中断
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String [] args) throws FileNotFoundException
{
int[] elf = new int[100000];
int cnt = 0;
Scanner input = new Scanner(new File("Elf.dat"));
while(input.hasNext())
{
elf[cnt] += input.nextInt();
if (input.next().equals("\n\n"));
{
cnt++;
}
}
int big = elf[0];
for (int lcv = 0; lcv < elf.length; lcv++)
{
if (big < elf[lcv])
{
big = elf[lcv];
}
}
System.out.println(big);
}
}
I'm trying this to detect the double line break我正在尝试检测双换行符
if (input.next().equals("\n\n"));
but its giving me errors.但它给了我错误。 how would i detect it
我怎么检测它
Welcome to Advent of Code 22.欢迎来到代码 22 的来临。
As a good rule, never mix nextXXX
methods with any other next
.作为一个好的规则,永远不要将
nextXXX
方法与任何其他next
方法混合使用。
To break up the Blocks you have 2 good options:要分解块,您有 2 个不错的选择:
split
by the \n\n
Combination\n\n
组合split
Here is another alternative way to do this sort of thing.这是执行此类操作的另一种替代方法。 read comments in code:
阅读代码中的注释:
public static void main(String[] args) throws FileNotFoundException {
List<Integer> elfSums; // Can grow dynamically whereas an Array can not.
int sum;
// 'Try With Resources' used here to auto close the reader and free resources.
try (Scanner input = new Scanner(new File("Elf.dat"))) {
elfSums = new ArrayList<>();
String line;
sum = 0;
while (input.hasNextLine()) {
line = input.nextLine();
if (line.trim().isEmpty()) {
elfSums.add(sum);
sum = 0; // Reset sum to 0 (new elf comming up)
}
// Does the line contain a string representation of a integer numerical value?
if (line.matches("\\d+")) {
// Yes...add to current sum value.
sum += Integer.parseInt(line);
}
}
}
if (sum > 0) {
elfSums.add(sum);
}
// Convert List to int[] Array (There are shorter ways to do this)
int[] elf = new int[elfSums.size()];
for (int i = 0; i < elfSums.size(); i++) {
elf[i] = elfSums.get(i);
// For the heck of it, display the total sum for this current Elf
System.out.println("Elf #" + (i+1) + " Sum: -> " + elf[i]);
}
/* The elf[] int array now holds the data you need WITHOUT
all those empty elements with the array. */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.