我想做的是创建一个程序,该程序创建并用用户输入填充数组,然后找到最小的数字并将其与数组的第一个单元格交换。
我遇到的最大麻烦是如何找到最小的整数但能够交换它,因为当我这样做时:
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);
}
}
}
关于java - 找到数组中最小的整数,然后将其与第一个单元格交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61268613/