0
請原諒我,如果程序很混亂或難以理解,我在趕時間。無論如何,我有這個程序應該得到一組數字的平均值,中位數和模式。出於某種原因,程序讀取除了每行最後一個數字之外的所有數字。
示例輸入:掃描儀不能讀取最後一個號碼
3
1 2 3 3 //doesn't read the last number "3"
10 10 10 10 10 10 10 10 10 10 //doesn't read the last number "10"
2 3 4 5 5 9 8 7 5 5 3 2 1 //doesn't read the last number "1"
輸出示例:
mean median mode
2.3 2.5 3.0
10.0 10.0 10.0
4.5 5.0 5.0
public class Mean
{
public static void main(String[] args) throws IOException
{
out.print("\f");
Scanner scan = new Scanner (new File ("mean.dat"));
DecimalFormat deci = new DecimalFormat("##.0");
String x = scan.nextLine();
double mean = 0, median = 0, mode = 0;
String numbers;
String[] nums;
double[] num;
double sum = 0;
int y;
double mid;
int count2;
int HighestCount = 0;
int p;
out.println("mean median mode");
while (scan.hasNext())
{
mean = 0.0;
median = 0.0;
mode = 0.0;
HighestCount = 0;
sum = 0.0;
numbers = scan.nextLine();
nums = numbers.split("[ ]");
double l = nums.length;
num = new double[(int)l];
for (p = 0; p < l - 1; p++)
{
num[p] = Double.parseDouble(nums[p]);
sum += num[p];
}
mean = (sum/l);
Arrays.sort(num);
mid = l/2.0;
mid = Math.round(mid);
if (l%2 == 1)
{
median = (num[(int)mid]);
}
else
{
median = ((num[((int)mid) + 1] + num[((int)mid)])/2.0);
}
for (int i = 0; i < l; ++i)
{
count2 = 0;
for (int j = i; j < l; ++j)
{
double z = num[i];
double zz = num[j];
int d = (int)z;
int f = (int)zz;
if (d == f)
++count2;
}
if (count2 > HighestCount)
{
HighestCount = count2;
mode = num[i];
}
else if (count2 == HighestCount)
{
mode = num[i];
}
}
out.printf("%4.1f \t %4.1f \t %4.1f", mean, median, mode);
out.println();
}
}
}
u能還貼什麼烏爾在Java文件導入 – fscore
檢查 'for循環' 因爲我有類似的問題,我對循環沒有迭代到最後一個元素 – fscore