猿问

问:java中数值数组的排序

我正在尝试按升序和降序对数字数组进行排序。我是初学者,所以使用以下链接Sort an array in Java。我正在尝试从用户那里获取输入作为数组的元素。

public class SortingofString {



public static void main(String[] args) {

    Scanner input=new Scanner(System.in);

    int Array1[];

 //   String Array2[];

    System.out.println("How many numaric elements: ");

    int n = input.nextInt();

    int[] array1 = new int[n];

    int number=input.nextInt();


    for(int i=0; i<n; i++){

        System.out.println("Enter number:");

       array1[i] = number;

        System.out.println("Original numeric array : "+Arrays.toString(Array1));

        Arrays.sort(Array1);

        System.out.println("Sorted numeric array : "+Arrays.toString(Array1));



    } 

}

}


Array1当我在第一个函数中传递我的 array_name 时发生错误toString。

System.out.println("Original numeric array : "+Arrays.toString(Array1));

错误说Initialize variable Array1。我该如何解决这个错误?


GCT1015
浏览 97回答 2
2回答

胡子哥哥

public static void main(String[] args) {&nbsp; &nbsp; Scanner input = new Scanner(System.in);&nbsp; &nbsp; //int Array1[];&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; System.out.println("How many numaric elements: ");&nbsp; &nbsp; int n = input.nextInt();&nbsp; &nbsp; int arr[] = new int[n];// solve 1st problem&nbsp; &nbsp; for (int i = 0; i < n; i++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter number: " +(i+1));&nbsp; &nbsp; &nbsp; &nbsp; int number = input.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; arr[i]=number;//init&nbsp; array&nbsp; by user input data&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("Original numeric array : " + Arrays.toString(arr));&nbsp; &nbsp; Arrays.sort(arr);&nbsp; &nbsp; System.out.println("Sorted numeric array : " + Arrays.toString(arr));}你还需要 2 导入import java.util.Arrays;import java.util.Scanner;

扬帆大鱼

Array1在 reading 后面移动(并重命名)n:System.out.println("How many numaric elements: ");int n = input.nextInt();int[] array1 = new int[n];也许使用输入的number:int number = input.nextInt();array1[i] = number;
随时随地看视频慕课网APP

相关分类

Java
我要回答