java - 找到数组中最小的整数,然后将其与第一个单元格交换

标签 java arrays

我想做的是创建一个程序,该程序创建并用用户输入填充数组,然后找到最小的数字并将其与数组的第一个单元格交换。

我遇到的最大麻烦是如何找到最小的整数但能够交换它,因为当我这样做时:

        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/

相关文章:

javascript - 查看一组对象并从其属性中删除未定义

javascript - 将对象的索引包含到数组中

javascript - 如何在javascript中使用递归打印数组中的元素

java - 在 Windows 上使用 Redis-cli 在 Redis 中加载 CSV 文件

java - RecyclerView 不滚动

java - Java中的重构: Duplicated attributes

c++ - 使用数组的指针间接寻址

java.lang.ClassCastException : com. sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl 无法转换为 javax.net.ssl.HttpsURLConnection

java - 我怎样才能 "force"某种背压来避免在 rxjava 中多次执行?

c - 数组中的最大数量