Java如何实现三个输入整数的最大值与最小值位置互换
实现思路
你当前的代码已经正确获取到了三个数的最大值、最小值,但要完成位置互换,首先需要确定最大值、最小值分别存储在first/second/third哪个变量中,仅拿到数值是无法完成位置替换的。
具体实现步骤
- 新增两个变量
maxIndex、minIndex,用来标记最大值、最小值的位置,用1对应第一个数,2对应第二个数,3对应第三个数 - 比对三个数的取值,给两个标记变量赋值
- 借助临时变量交换对应位置的数值
- 输出交换后的三个数验证结果
修改后的完整代码
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("交换三个数中最大值和最小值位置的程序"); System.out.println("请输入第一个数:"); int first = scanner.nextInt(); System.out.println("请输入第二个数:"); int second = scanner.nextInt(); System.out.println("请输入第三个数:"); int third = scanner.nextInt(); int largest = largest(first, second, third); int smallest = smallest(first, second, third); System.out.printf("输入的三个数为 %d、%d、%d,最大值是:%d %n", first, second, third, largest); System.out.printf("输入的三个数为 %d、%d、%d,最小值是:%d %n", first, second, third, smallest); // 确定最大最小值的位置 int maxIndex = 0; int minIndex = 0; if (first == largest) maxIndex = 1; else if (second == largest) maxIndex = 2; else maxIndex =3; if (first == smallest) minIndex = 1; else if (second == smallest) minIndex = 2; else minIndex =3; // 交换对应位置的值 int temp; if (maxIndex == 1 && minIndex == 2) { temp = first; first = second; second = temp; } else if (maxIndex ==1 && minIndex ==3) { temp = first; first = third; third = temp; } else if (maxIndex ==2 && minIndex ==1) { temp = second; second = first; first = temp; } else if (maxIndex ==2 && minIndex ==3) { temp = second; second = third; third = temp; } else if (maxIndex ==3 && minIndex ==1) { temp = third; third = first; first = temp; } else if (maxIndex ==3 && minIndex ==2) { temp = third; third = second; second = temp; } // 输出交换后的结果 System.out.printf("交换最大最小值位置后的三个数为:%d、%d、%d", first, second, third); scanner.close(); } public static int largest(int first, int second, int third) { int max = first; if (second > max) { max = second; } if (third > max) { max = third; } return max; } public static int smallest(int first, int second, int third) { int min = first; if (second < min) { min = second; } if (third < min) { min = third; } return min; } }
优化方案
如果不想写多分支判断,可以把三个数放到数组中处理,逻辑更简洁:
// 把三个数存入数组 int[] nums = {first, second, third}; int maxIdx = 0, minIdx = 0; for (int i = 1; i < nums.length; i++) { if (nums[i] > nums[maxIdx]) maxIdx = i; if (nums[i] < nums[minIdx]) minIdx = i; } // 交换数组对应位置的值 int temp = nums[maxIdx]; nums[maxIdx] = nums[minIdx]; nums[minIdx] = temp; // 把数组值写回原变量 first = nums[0]; second = nums[1]; third = nums[2];
内容的提问来源于stack exchange,提问作者D. Georgieva
相关产品推荐
相关产品推荐

