gpt4 book ai didi

java - java读取txt文件中的分数

转载 作者:行者123 更新时间:2023-12-01 14:37:17 25 4
gpt4 key购买 nike

我一直在互联网上寻找帮助,但找不到它,所以我只能发帖。

我有一个格式如下的 txt 文件

1/2 0 1/66/11 1/6 2/10

我需要读取每个单独的分数,并在名为 BigFraction(num, denom) 的函数中输入分子和分母。

我调用阅读器并将其输出为字符串。然后我分割空格以获得各个分数作为字符串将它们输入到我的辅助方法 strToBF 中,它在正斜杠上分开并输入分子和分母。

但它不起作用,任何帮助将不胜感激

我的主要方法

            String file = fileToString(fileName);
file.replaceAll("(.*)\\/(.*)", "a");
String[] splitFile = file.split(" ");

BigFraction conditionA = stringToBF(splitFile[0]);
BigFraction c1A = stringToBF(splitFile[1]);
BigFraction c2A = stringToBF(splitFile[2]);
ConditionalTwoCoinChannel CTCCA = new ConditionalTwoCoinChannel(conditionA, new TwoCoinChannel(c1A, c2A));

BigFraction conditionB = stringToBF(splitFile[3]);
BigFraction c1B = stringToBF(splitFile[4]);
BigFraction c2B = stringToBF(splitFile[5]);
ConditionalTwoCoinChannel CTCCB = new ConditionalTwoCoinChannel(conditionB, new TwoCoinChannel(c1B, c2B));

List<ConditionalTwoCoinChannel> outputList = new ArrayList<ConditionalTwoCoinChannel>();

outputList.add(CTCCA);
outputList.add(CTCCB);

return outputList;

和我的两个辅助方法

private static String fileToString(String file)
throws FileNotFoundException, IOException {

BufferedReader fileReader = new BufferedReader(new FileReader(file));
StringBuilder sBuilder = new StringBuilder();
String fileLine = fileReader.readLine();

try {
while (fileLine != null) {
sBuilder.append(fileLine);
sBuilder.append(" ");
fileLine = fileReader.readLine();
}
} catch (FileNotFoundException e1) {
throw new RuntimeException("file not found");
} catch (IOException e2) {
throw new RuntimeException("Input Error");
}
finally {
fileReader.close();
}


return sBuilder.toString();




private static BigFraction stringToBF(String str){

if (strToInt(str) == 0) {
return BigFraction.ZERO;
}
else {
String[] strSplit = str.split("(.*)a(.*)");
int numerator = strToInt(strSplit[0]);
int denominator = strToInt(strSplit[1]);
return new BigFraction(numerator, denominator);
}
}

最佳答案

这个

String[] strSplit = str.split("(.*)a(.*)");

无法分割“1/2”

尝试

String[] strSplit = str.split("/");

关于java - java读取txt文件中的分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16370969/

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