所以我有一个列表,我应该返回平均值,最高值和最低值。 我的价值最高,平均值也很低。我无法弄清楚如何提示程序返回最低值。 这是我的代码。
import java.util.Scanner;
import java.io.*;
public class PopData
{
public static void main(String[] args) throws IOException
{
int sum = 0;
int average = 0;
int total = 42;
int high = 0;
int low = 0;
File file = new File("USPopulation.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
int number = inputFile.nextInt();
sum = sum + number;
average = sum / total;
if (number >= high) {
high = number;
}
}
inputFile.close();
System.out.println("The average of the numbers is " + average);
System.out.println(high);
System.out.println(low);
}
}
答案 0 :(得分:0)
使用与较低级别相同的技术...
import java.util.Scanner;
import java.io.*;
public class PopData
{
public static void main(String[] args) throws IOException
{
int sum = 0;
int average = 0;
int total = 42;
int high = 0;
Integer low = null;
File file = new File("USPopulation.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
int number = inputFile.nextInt();
sum = sum + number;
average = sum / total;
if (number >= high) {
high = number;
}
if( low == null || number < low)
low = number;
}
inputFile.close();
System.out.println("The average of the numbers is " + average);
System.out.println(high);
System.out.println(low);
}
}
您也可以使用int
而不是整数,在这种情况下,您将int设置为Integer.MAX_VALUE
import java.util.Scanner;
import java.io.*;
public class PopData
{
public static void main(String[] args) throws IOException
{
int sum = 0;
int average = 0;
int total = 42;
int high = 0;
int low = Integer.MAX_VALuE;
File file = new File("USPopulation.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
int number = inputFile.nextInt();
sum = sum + number;
average = sum / total;
if (number >= high) {
high = number;
}
if(number < low)
low = number;
}
inputFile.close();
System.out.println("The average of the numbers is " + average);
System.out.println(high);
System.out.println(low);
}
}