java - 查找数组中的最小整数,然后将其与第一个单元格交换
问题描述
我要做的是创建一个程序,该程序使用用户输入创建并填充数组,然后找到最小的数字并与数组的第一个单元格交换。
我遇到的最大麻烦是如何找到最小的整数但能够交换它,因为当我这样做时:
for(int i = 0; i < swap.length; i++){
if(smallest > swap[i]){
smallest = swap[i];
它使它变成一个整数,当我尝试交换它时。
int temp = swap[0];
swap[0] = smallest;
smallest = temp;
它没有给我想要的输出,我想知道如何找到最小的数字并保留数组单元格编号,以便我可以使用它进行交换。
这是完整的当前代码:
import java.util.Scanner;
import java.util.Arrays;
public class SmallestSwap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Size of array?");
int n = sc.nextInt();
int [] swap = new int[n];
int smallest = Integer.MAX_VALUE;
for(int i = 0; i <swap.length; i++){
System.out.println("Please enter a number: ");
swap[i] = sc.nextInt();
}
for(int i = 0; i < swap.length; i++){
if(smallest > swap[i]){
smallest = swap[i];
}
}
int temp = swap[0];
swap[0] = smallest;
smallest = temp;
System.out.println("\n");
for(int element : swap){
System.out.println(element);
}
}
}
解决方案
这是指针和值的问题。
smallest = swap[i];
不保存对数组中真实项目的引用swap[i]
。在smallest
你会发现只有最小值。因此,如果您要交换值,则必须保存索引。这是代码
import java.util.Scanner;
import java.util.Arrays;
public class swap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Size of array?");
int n = sc.nextInt();
int [] swap = new int[n];
int index_smallest = 0;
int smallest = Integer.MAX_VALUE;
for(int i = 0; i <swap.length; i++){
System.out.println("Please enter a number: ");
swap[i] = sc.nextInt();
}
for(int i = 0; i < swap.length; i++){
if(smallest > swap[i]){
smallest = swap[i];
index_smallest = i;
}
}
int temp = swap[0];
swap[0] = swap[index_smallest];
swap[index_smallest] = temp;
System.out.println("\n");
for(int element : swap){
System.out.println(element);
}
}
}
推荐阅读
- python - on_member_ban 事件在我的 cog 上不起作用 | discord.py 重写
- regex - 刮掉这个嘈杂的价格标签的正确方法
- android - EACCES(权限被拒绝)也适用于我的应用程序创建的文件?
- html - 从 \\localhost\c$ 打开 Google 地球地标时缺少气球内容是否有修复?
- android - 如何为颜色选择器添加淡入淡出效果
- javascript - 如何在 NodeJS 中结合来自 2 个不同 var 的日期和时间
- python - 完全更新 matplotlib 图(不附加数据)
- vba - 运行时错误“1004”应用程序定义或对象定义错误
- google-cloud-platform - 光束中大窗口的间隔触发
- node.js - 如何使用 pg 从 postgres 存储过程(或函数)中检索结果集