一、要求
首先定义两个数组,用来表示下列关系表:
水位:112,115,113,110,111,114
库容:5656,5954,5703,5500,5642,5841
1、将两个数组分别按从小到大排序
2、输入任意一个水位,输出对应库容
二、代码实现:
从小到大排序,这里用的是冒泡排序法(两个数组代码结构相同):
package book2;
import java.util.Scanner;
public class Test02 {
static int temp;
public static void main(String[] args) {
int[] waterLevel = {112, 115, 113, 110, 111, 114};
int[] capacity = {5656, 5954, 5703, 5500, 5642, 5841};
getSort(waterLevel, capacity);
correspond(waterLevel, capacity);
}
public static void getSort(int[] water, int[] capacity) {
// 冒泡排序
System.out.print("水位数:");
for (int i = 0; i < water.length; i++) {
for (int j = i + 1; j < water.length; j++) {
if (water[i] > water[j]) {
temp = water[i];
water[i] = water[j];
water[j] = temp;
}
}
System.out.print(water[i] + " ");
}
输入任意一个水位,输出对应库容:
// 水位对应的水库容量
public static void correspond(int[] water, int[] capac) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入水位:");
temp = sc.nextInt();
for (int i = 0; i < water.length; i++) {
if (water[i] == temp) {
System.out.println("水位对应的库容为:" + capac[i]);
}
}
}