项目1:全国各省平均寿命如图所示,请使用一维数组和方法,编写程序实现计算并输出全国平均寿命,最高平均寿命,最低平均寿命,平均寿命从高到底排序并输出。 java
时间: 2024-09-19 18:09:09 浏览: 55
在Java中,你可以创建一个一维整型数组来存储全国各省的平均寿命数据。首先,你需要初始化数组并将省份名称和平均寿命对应起来。然后,你可以定义一些方法来完成所需的功能:
```java
public class AverageLife {
private int[] life expectancies; // 存储平均寿命的一维数组
private String[] provinces; // 存储省份名称
public AverageLife(int[] lifeExpectancies, String[] provinces) {
this.lifeExpectancies = lifeExpectancies;
this.provinces = provinces;
}
// 计算并返回全国平均寿命
public double calculateNationalAverage() {
int sum = 0;
for (int expectancy : lifeExpectancies) {
sum += expectancy;
}
return (double) sum / lifeExpectancies.length;
}
// 找出最高的平均寿命
public int findMaxLifeExpectancy() {
int max = lifeExpectancies[0];
for (int i = 1; i < lifeExpectancies.length; i++) {
if (lifeExpectancies[i] > max) {
max = lifeExpectancies[i];
}
}
return max;
}
// 找出最低的平均寿命
public int findMinLifeExpectancy() {
int min = lifeExpectancies[0];
for (int i = 1; i < lifeExpectancies.length; i++) {
if (lifeExpectancies[i] < min) {
min = lifeExpectancies[i];
}
}
return min;
}
// 按照平均寿命降序排列并输出
public void sortAndPrint() {
int[] sortedLifeExpectancies = Arrays.copyOf(lifeExpectancies, lifeExpectancies.length);
Arrays.sort(sortedLifeExpectancies);
for (int i = sortedLifeExpectancies.length - 1; i >= 0; i--) {
System.out.println(provinces[i] + ": " + sortedLifeExpectancies[i]);
}
}
// 主函数用于测试
public static void main(String[] args) {
// 假设这里是你实际的数据填充
int[] lifeExpectancies = {75, 80, 78, 82, 76}; // 平均寿命示例
String[] provinces = {"省份A", "省份B", "省份C", "省份D", "省份E"}; // 省份名称示例
AverageLife avgLife = new AverageLife(lifeExpectancies, provinces);
System.out.println("全国平均寿命: " + avgLife.calculateNationalAverage());
System.out.println("最高平均寿命: " + avgLife.findMaxLifeExpectancy());
System.out.println("最低平均寿命: " + avgLife.findMinLifeExpectancy());
avgLife.sortAndPrint();
}
}
```
阅读全文