gpt4 book ai didi

Java在子串中找到两个中位数

转载 作者:行者123 更新时间:2023-11-30 08:13:26 27 4
gpt4 key购买 nike

这里是java新手,我有一个菜鸟问题。

我最近收到了这个 txt 文件:

Albuquerque, New Mexico, 5352 feet, 202.3°
Denver, Colorado, 5280 feet, 202.4°
Minneapolis, Minnesota, 841 feet, 210.5°
Birmingham, Alabama, 644 feet, 210.8°
Detroit, Michigan, 639 feet, 210.8°
Miami, Florida, 11 feet, 211.9°
Burj Khalifa, Dubai, 2717 feet, 207.1°
CN Tower, Toronto, 1815 feet, 208.7°

并被要求找到并打印出两个中位数。问题是当我尝试使用 Arrays.sort() 时不断收到错误。

public static void main(String[] args) {
File mf = new File("C:\\file.txt");
ArrayList<String> inData = new ArrayList<String>();
String strline;

try {
FileInputStream fstream = new FileInputStream(mf);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
while ((strline = br.readLine()) != null) {
strline = strline.trim();
if ((strline.length() != 0)) {
inData.add(strline);
}
}
br.close();
} catch (Exception e) {
System.err.println("Error CANNOT FIND FILE!");
}

//Calc median start
double median;
for (int i = 0; i < inData.size(); i++) {
String[] word = inData.get(i).split(", ");
double m = Double.parseDouble(word[3].substring(0, 5));
Arrays.sort(m);
if (m.length % 2 == 0) {
double middleNumOne = m[m.length / 2 - 0.5]
double middleNumTwo = m[m.length / 2 + 0.5]
System.out.println("Median:" + middleNumOne + "and" + middleNumTwo);
}
}
}

这就是我到目前为止所拥有的。有人可以帮助我,告诉我我错过了什么吗?

最佳答案

只是为了向您说明这一点,这就是您需要更改的内容:

double[] median = new double[inData.size()];

for (int i=0; i < inData.size(); i++) {
String[] word = inData.get(i).split(", ");
double m = Double.parseDouble(word[3].substring (0,5));
median[i] = m;
}

Arrays.sort(median);

然后,代码中此点之后对 m 的每个引用都应更改为 median

关于Java在子串中找到两个中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017446/

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