我有一个名为numbers.txt的文本文件,里面有很多数字。我需要找到数字的平均中位数和众数。我可以读取文件,但是我不知道更多。
import java.io.File;
import java.util.Scanner;
public class Terms {
public static void main(String[] args)throws Exception {
File file =
new File("C:\\Users\\coderva.org\\Documents\\numbers.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
答案 0 :(得分:0)
您可以这样创建数字列表:
List<Integer> numberList = new ArrayList<>();
while (sc.hasNextInt())
numberList.add(sc.nextInt());
或者当您有双打或浮空时:
List<Double> numberList = new ArrayList<>();
while (sc.hasNextDouble())
numberList.add(sc.nextDouble());
List<Float> numberList = new ArrayList<>();
while (sc.hasNextFloat())
numberList.add(sc.nextFloat());
从那里可以计算出平均值,如下所示:
sum = numberList.stream().mapToInt(Integer::intValue).sum();
average = sum / numberList.size();
对于所需的其他属性,依此类推。
注意:求和类型和平均值取决于您从文件中读取的类型。
答案 1 :(得分:0)
根据均值,中位数和众数的定义:
public static void main(String[] args) {
File file = new File("C:\\Users\\coderva.org\\Documents\\numbers.txt");
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
return;
}
ArrayList<Float> list = new ArrayList<Float>();
while (sc.hasNextFloat())
list.add(sc.nextFloat());
int size = list.size();
if (size == 0) {
System.out.println("Empty list");
return;
}
Collections.sort(list);
for (int i = 0; i < size; i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
// mean value, classical way
float sum = 0;
for (float x : list) {
sum += x;
}
float mean = sum / size; // mean as integer
//median
float median;
if (size % 2 == 0) {
float x1 = list.get(size / 2 - 1);
float x2 = list.get(size / 2);
median = (x1 + x2) / 2;
} else {
median = list.get(size / 2);
}
//mode
Float mode = null;
int counter = 1;
for (int i = 0; i < size; i++) {
int freq = Collections.frequency(list, list.get(i));
if (freq > counter) {
mode = list.get(i);
counter = freq;
}
}
System.out.println("Mean=" + mean);
System.out.println("Median=" + median);
if (mode == null) {
System.out.println("No mode found");
} else {
System.out.println("Mode=" + mode);
}
}