orenbdlv
orenbdlv

Reputation: 13

input values into array from Scanner

The user needs to put 10 numbers.
And put them into an array.
And introduce them from the smallest to the largest.

This is my code

import java.util.Scanner;

public class q1 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int arr[] = new int[10];
        System.out.println("please enter 10 rundom numbers: ");
        for (int i = 0; i < arr.length; i++) {
            int number = input.nextInt();
            System.out.println(number);
        }
    }
}

Upvotes: 1

Views: 1245

Answers (3)

csalmhof
csalmhof

Reputation: 1860

If you need to sort it at the time you are inserting them into the array, you can walk throw the existing numbers and insert it at the position you want it.

Something like that (InsertionSort):

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  int arr[] = new int[10];

  System.out.println("please enter 10 random numbers: ");

  //store 10 numbers into the array
  for (int i = 0; i < arr.length; i++) {
    int number = input.nextInt();

    //switch all values in array which are > number one to the right
    int j = i;
    while (j > 0 && arr[j-1] > number) {
      arr[j] = arr[j-1];
      j--;
    }
    //insert number at correct position;
    arr[j] = number;
  }

  System.out.println(Arrays.toString(arr));
}

Anyway the better solution (imho) would be to insert the numbers at the position that they are given by the user and afterwords use Arrays.sort like this:

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  int arr[] = new int[10];

  System.out.println("please enter 10 random numbers: ");

  //store 10 numbers into the array
  for (int i = 0; i < arr.length; i++) {
    arr[i] = input.nextInt();
  }

  Arrays.sort(arr);
  System.out.println(Arrays.toString(arr));
}

Upvotes: 1

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

public static void main(String... args) {
    Scanner scan = new Scanner(System.in);
    int[] arr = readRandomNumbers(scan, 10);
    Arrays.sort(arr);
    System.out.println("Sorted number: " + Arrays.toString(arr));
}

private static int[] readRandomNumbers(Scanner scan, int total) {
    int[] arr = new int[total];

    System.out.format("please enter %d random numbers:\n", total);

    for (int i = 0; i < arr.length; i++) {
        System.out.format("%d: ", i + 1);
        arr[i] = scan.nextInt();
    }

    return arr;
}

Upvotes: 0

shikida
shikida

Reputation: 505

Every time you enter a new number, you walk in your array and if the new number is greater than the next one, you switch them each other.

Repeat until you get to the end of the array, so you'll keep your array sorted.

Upvotes: 0

Related Questions