如何打印随机插入排序的数组内容以及随机数之前的单词?

2g32fytz  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(380)

这段代码排序并打印随机数,这是我想要的。我缺少的是数字前面的单词。我是java新手,但更精通python。我希望每一个随机数在打印出来的时候都说:
结果[0]=_
结果[1]=_
结果[2]=_
结果[3]=_
而不必一个接一个地把这些都写进代码里。在python中,下面的代码将打印出所有内容。 print(“result[“,I,”] =“, result[I]) ```
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Size of Random Number");
int n = input.nextInt();
Random random = new Random();
int[] result = random.ints(n, -n, n).toArray();

    Arrays.stream(result).forEach(System.out::println);
    System.out.println("\n");

    int len = result.length;
    System.out.println("Insertion Sort");
    for(int i=1; i<len; i++){
        int j;
        int key = result[i];
        for (j=i-1; (j >= 0 && result[j] > key); j--) { 
            result[j + 1] = result[j]; 
            result[j+1] = key;
            for( i = 0; i < len; i++){
                System.out.println("result[" + (i) + "] =" );
                Arrays.stream(result).forEach(System.out::println);
                System.out.println("\n");
            }  
        } 

    }
}
6jjcrrmo

6jjcrrmo1#

问题是您已经将print语句放入嵌套循环中。另外,在嵌套循环的每次迭代中都要打印整个数组。只要把它拿出来,在一次迭代中只打印一个元素。

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Size of Random Number: ");
        int n = input.nextInt();
        Random random = new Random();
        int[] result = random.ints(n, -n, n).toArray();

        Arrays.stream(result).forEach(System.out::println);
        System.out.println("\n");

        // Insertion sort
        int len = result.length;
        for (int i = 1; i < len; ++i) {
            int key = result[i];
            int j = i - 1;
            while (j >= 0 && result[j] > key) {
                result[j + 1] = result[j];
                j = j - 1;
            }
            result[j + 1] = key;
        }

        System.out.println("After sorting: ");
        for (int i = 0; i < len; i++) {
            System.out.println("result[" + (i) + "] =" + result[i]);
        }
    }
}

示例运行:

Enter Size of Random Number: 5
0
-5
-3
2
1

After sorting: 
result[0] =-5
result[1] =-3
result[2] =0
result[3] =1
result[4] =2

注意:我还纠正了您的排序逻辑。在互联网上有数百个教程可以学习插入排序,例如,你可以检查这一个。

a6b3iqyw

a6b3iqyw2#

您只需替换此行: System.out.println("result[" + (i) + "] =" ); 对于该行: System.out.println("result[" + (i) + "] =" + result[i]); 或者你可以用 String.format : System.out.println(String.format("result[%d] = %s", i, result[i])); 您还必须删除其他两行:

// here you are printing again all the numbers so is not necessary
Arrays.stream(result).forEach(System.out::println); 

// here you are adding another linebreak, but using println add the linebreak automatically
System.out.println("\n");
tv6aics1

tv6aics13#

这就是你要找的吗?

for(i = 0; i < result.len; i++){
    System.out.println("result[" + i + "] = " + result[i]);
}

相关问题