首页 > 解决方案 > 查找数组中的最小整数,然后将其与第一个单元格交换

问题描述

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

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

        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);
    }
}

}

标签: javaarrays

解决方案


这是指针和值的问题。

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);
    }
  }
}



推荐阅读