如何更改数组中元素的位置

时间:2014-08-08 21:49:03

标签: java arrays

我正在编写一个程序,它从键盘中取出10 Integer并将它们列在一个索引为0-9的数组中,并报告数组中最小数字的位置。如果最小的数字具有除0以外的任何其他位置,则程序应该将最小数字输入的位置切换为数组中第一个位置的数字:

import java.util.Scanner;

public class q35 {

    public static void main(String args[]) {

        Scanner tastatur = new Scanner(System.in);

        int[] helTall = new int[10];
        int input;

        int lowest = Integer.MAX_VALUE;

        for(int i=0;i<helTall.length;i++) {

            System.out.println("Integers? ");
            input = tastatur.nextInt();  

            if (input < lowest) {
                lowest = input;
            }

            helTall[i] = input;

        }

        for (int i = 0; i < helTall.length; i++) {
            helTall[0] = lowest;
            System.out.println(helTall[i]);
        }

        System.out.println("Lowest number is " + lowest);
    }
}

唯一的问题是,不是使用helTall[0]处的数字更改最低编号的位置,而是使用最低helTall[0]完全替换序列Integer中的第一个数字,这样,如果我的输入为4 5 63 23 6 -4 7 33 23 99,则输出变为-4 5 63 23 6 -4 7 33 23 99(因为您可以看到第一个输入数字被完全删除),但它应该是-4 5 63 23 6 4 7 33 23 99任何提示/建议/解决方案?提前谢谢。

4 个答案:

答案 0 :(得分:1)

您应该跟踪最低编号的索引(每次编写lowest = input;时都应添加lowestIndex=i;
然后helTall[lowestIndex]将是最低的数字 因此,您将helTall[lowestIndex]helTall[0]交换,而不是仅覆盖helTall[0]的值。

我认为用文字描述解决方案已经足够了,但我想这不是......

int lowest = Integer.MAX_VALUE;
int lowestIndex = 0;
for(int i=0;i<helTall.length;i++){
  System.out.println("Integers? ");
  input = tastatur.nextInt();  
  if (input < lowest){
    lowest = input;
    lowestIndex = i;
  }
  helTall[i]=input;
}
// swap the numbers
if (lowestIndex > 0) {
  int temp = lowest;
  helTall[lowestIndex] = helTall[0];
  helTall[0] = temp;
}
// display output
for (int i = 0; i < helTall.length; i ++) {
  System.out.println(helTall[i]);
}

答案 1 :(得分:0)

这部分错了:

for (int i = 0; i < helTall.length; i ++) {
    helTall[0]=lowest;
    System.out.println(helTall[i]);
}

首先,您不需要重复(10次)将lowest放入helTall[0]。让我们首先将其移到外面,这样只做一次:

helTall[0]=lowest;
for (int i = 0; i < helTall.length; i ++) {
    System.out.println(helTall[i]);
}

接下来,我们放在循环外面的行会覆盖helTall [0],而不考虑其中的内容。我们需要在其他地方临时保存该号码,然后覆盖该点,以便我们可以用它来覆盖最低号码所在的地点:

int numberAtLocationZero = helTall[0];
helTall[0]=lowest;
// Now, on this line we need to write helTall[lowestNumberIndex] = numberAtLocationZero;
for (int i = 0; i < helTall.length; i ++) {
    System.out.println(helTall[i]);
}

在上面的代码中我写了一条评论。它依赖于你要么知道数组中最低的数字在哪里,要么再次找到它。如果您在代码中添加一个新变量,该变量会接收名为lowestNumberIndex的值,并在每次检测到新的最低数字时更新该变量,那么如果您取消注释我的评论,那么您就已经完成了很多工作。

答案 2 :(得分:0)

在使用新的最低输入数字覆盖数组之前,需要一个单独的变量来存储数组底部的内容。

helTall[0]=lowest;

应该按

进行
int placeholder = helTall[0]

然后是

hellTall[i] = placeholder;

这样,你最终会交换两个数组元素,第一个与最低数组交换。这是你想要完成的吗?这使得大多数数组都未排序。

答案 3 :(得分:-1)

使用嵌套for循环找到最低的no,然后通过与array比较找到它的索引 并交换第一个位置的值和最低值不存在的索引值

相关问题