所需输出:
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,我不明白为什么。
最佳答案
不要将您的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);
关于java - 我的所有输出都收到 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28471615/