期望输出:
Total: 55.0
Average: 5.5
Minimum Value: 1.0
Maximum Value: 10.0
The data being used is: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
我的代码是
import java.util.*;
import java.io.*;
public class CH8_11 {
//Constants Declaration
//*********************
public static void main(String[] args) throws FileNotFoundException
{
// TODO Auto-generated method stub
//Variable Declaration Section
//****************************
int[] numbers;
int SIZE;
int i;
int max;
int min;
int total;
double average;
// Variables Initialization Section
//*********************************
File file = new File("C:\\testing1.txt");
Scanner scanner = new Scanner(file);
SIZE = 0;
max = 0;
min = Integer.Max_VALUE;
i = 0;
total = 0;
average = 0.0;
//Keyboard
//********
// Code Section
//*************
while(scanner.hasNext())
{
SIZE++;
scanner.next();
}
while(scanner.hasNext() && i < numbers.length)
{
numbers[i] = scanner.nextInt();
i++;
}
for(int j = 1; j < numbers.length; j++)
{
if(numbers[j] > max)
max = numbers[j];
}
for(int j = 1; j < numbers.length; j++)
{
if(numbers[j] < min)
min = numbers[j];
}
for(int j = 0; j < numbers.length; j++)
{
total += numbers[j];
average = total / (double)numbers.length;
}
//Output Section
//**************
System.out.println("Numbers being used: "+ java.util.Arrays.toString(numbers));
System.out.print("---------------------------------------------------");
System.out.print("\nMaximum Value: " + max);
System.out.print("\n-----------------");
System.out.print("\nMinimum Value: " + min);
System.out.print("\n-----------------");
System.out.print("\nAverage: " + average);
System.out.print("\n-----------------");
System.out.print("\nTotal: " + total);
//Resource Cleaning
//*****************
scanner.close();
}
}
感谢社区的帮助,我修复了最低价值解决方案。我将我的代码修改为以下评论之一的建议,允许数组成为文件的大小,因此它不是固定大小。但现在我收到所有输出的0,我无法弄清楚原因。
答案 0 :(得分:3)
请勿将min
初始化为
min = numbers[0];
这会在0
处放置,并且必定是给定数组值的最小值。将其初始化为Integer.MAX_VALUE
min = Integer.MAX_VALUE;
或者,只需使用您在循环之前计算的最大可用值
for(int j = 0; j < numbers.length; j++)
{
if(numbers[j] > max)
max = numbers[j];
}
min = max;
for(int j = 0; j < numbers.length; j++)
{
if(numbers[j] < min)
min = numbers[j];
}
另请注意,您需要开始使用int j = 0
进行迭代。否则,您的代码在计算最大值和最小值时忽略第一个数组值。
计算文件中可用的整数数
File file = new File("C:\\testing1.txt");
Scanner scanner = new Scanner(file);
SIZE = 0;
// count the numbers
while(scanner.hasNext()) {
SIZE++;
scanner.next()
}
numbers = new int[SIZE];
// reopen the scanner
scanner.close();
scanner = new Scanner(file);
答案 1 :(得分:1)
用0初始化min
然后检查输入的每个值是否小于该值。没有,所以它保持为空。
使用较高的值min
Integer.MAX_VALUE
更新:
您的代码中还有另一个错误:您使用1而不是0启动for循环,跳过数组的第一个元素