-2

I am trying to sort a numeric array in ascending and descending order. I am beginner so using the following link Sort an array in Java . I am trying to get input from user as array's elements.

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


    } 
}
}


The error occurs when i pass my array_name Array1 in first toString function.
System.out.println("Original numeric array : "+Arrays.toString(Array1));
Error says Initialize variable Array1 . How can i resolve this error?

Ijlal H
  • 69
  • 1
  • 8

2 Answers2

0

Move (and rename) Array1 behind reading n:

System.out.println("How many numaric elements: ");
int n = input.nextInt();
int[] array1 = new int[n];

And maybe use the entered number:

int number = input.nextInt();
array1[i] = number;
  • 2
    Please edit your question and add your code as it is now. What error do you get? –  Jul 23 '19 at 10:05
  • You did not change your code like I wrote above. Remove the line containing `int Array1[];` and change every occurenc of `Array1` to `array1`. –  Jul 23 '19 at 10:14
  • according to another answer i have changed my code and it is working. Thank u so much @Lutz Horn – Ijlal H Jul 23 '19 at 10:18
  • Yes i have understand @Lutz Horn. You are right i changed my array name Array1 to arr – Ijlal H Jul 23 '19 at 10:21
0
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    //int Array1[];     
    System.out.println("How many numaric elements: ");

    int n = input.nextInt();
    int arr[] = new int[n];// solve 1st problem
    for (int i = 0; i < n; i++) {
        System.out.println("Enter number: " +(i+1));
        int number = input.nextInt();
        arr[i]=number;//init  array  by user input data
    }
    System.out.println("Original numeric array : " + Arrays.toString(arr));
    Arrays.sort(arr);
    System.out.println("Sorted numeric array : " + Arrays.toString(arr));
}

you also need 2 import

import java.util.Arrays;
import java.util.Scanner;
Istiaque Hossain
  • 2,157
  • 1
  • 17
  • 28