gpt4 book ai didi

java - 如何将不同的行分割成字符串

转载 作者:行者123 更新时间:2023-12-01 10:19:38 25 4
gpt4 key购买 nike

我正在尝试解决 Panacea - truth or lie挑战。

基本上,我必须检查文本文件(可以包含多行)中两组数字的总和是否相等。第一组是十六进制数,第二组是二进制数;两组的分离是由数字 9 完成的(我在使用 split 和参数 | 作为分隔表达式时遇到问题,你知道为什么吗?)

输入示例:

64 6e 78 9 100101100 11110

5e 7d 59 9 1101100 10010101 1100111

如果它运行一次,代码没问题,但进入 while 循环时,我会收到 NumberFormatExceptions

这是我的最终代码:

import java.util.*;
import java.io.*;

public class test {
public static void main (String[] args) throws IOException {
BufferedReader buff = new BufferedReader(new FileReader ("C:\\Users\\Steel\\Desktop\\JAVA\\somme\\som.txt"));

int somma_bin;
int somma_hex;
int i;
String ciao = "9";
List<String> binehex = new ArrayList<>();
String prova;
while ((prova = buff.readLine()) != null) {
somma_bin = 0;
somma_hex = 0;
binehex = Arrays.asList(prova.split(" "));
i = 0;

while (!(binehex.get(i)).equals(ciao)) {
somma_hex += Integer.parseInt(binehex.get(i), 16);
i++;
}

i++;
while (i < (binehex.size()-1)) {
somma_bin += Integer.parseInt(binehex.get(i), 2);
i++;
}

if (somma_bin == somma_hex) {
System.out.println("true");
} else {
System.out.println("false");
}
System.out.println(prova);
}
}
}

最佳答案

除了有很多代码之外,我看不出有什么明显的问题。

尝试更多的结构:

String line; // given a line
String[] parts = line.split(" 9 ");
int sumHex = Arrays.stream(parts[0].split(" ")).mapToInt(s -> Integer.parseInt(s, 16)).sum();
int sumBin = Arrays.stream(parts[1].split(" ")).mapToInt(s -> Integer.parseInt(s, 2)).sum();
System.out.println(sumHex == sumBin);

我不确定 "|" 的相关性拆分有什么相关性,因为这不在您发布的代码中,但是如果您想在管道上拆分,则必须对它进行分隔,因为管道char 在正则表达式中具有特殊含义:

string.split("\\|");

关于java - 如何将不同的行分割成字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35685164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com