0

I'm trying to solve a java question, where I have to sort the numbers in ascending orders. My code works, until I put a negative in integer in it.

import java.util.Scanner;
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();

        int[] numbers = new int[input];

        for (int i = 0; i < numbers.length; i++) {
            int a = sc.nextInt();
            numbers[a] += a;
        }
        for (int i = 1; i < numbers.length; i++) {
                System.out.println(i + " " + numbers[i] / i);
        }
    }
}

I want to set the amount of numbers in the line 9 as input, but I face errors when I enter bigger values or negative integers. Any helps plz?

This is basically what I need to sort out:

input:

5
-3
100
-1
-2
-1

output:

-3 1
-2 1
-1 2
100 1
6
  • hmm numbers[a] += a; if a == -1 numbers[-1] will not work Commented Nov 22, 2018 at 2:22
  • numbers[a] += a; what happened to i? and why are you using addition? and where is the sort? Commented Nov 22, 2018 at 2:22
  • @ElliottFrisch I think he is trying to insert into the array at the index where the index is the number inputted Commented Nov 22, 2018 at 2:23
  • @ScaryWombat In which case, he wants numbers[i] = a; and then he can get on with sorting. What do you make of System.out.println(i + " " + numbers[i] / i); though? Commented Nov 22, 2018 at 2:24
  • @ElliottFrisch Yes, he should, but I guess he thought he could cheat Commented Nov 22, 2018 at 2:25

1 Answer 1

1

Arrays.sort() is a built-in function to help you sort the array

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int input = sc.nextInt();
    int[] numbers = new int[input];

    for (int i=0; i <numbers.length; i++) {
        int a = sc.nextInt();
        numbers[i] = a;
    }
    sc.close();

    Arrays.sort(numbers);

    int temp=numbers[0];
    int count=1;
    for(int i=1; i<numbers.length; i++){
        if(numbers[i]==temp){
            count++;
        }else{
            System.out.println(temp + " " + count);
            count=1;
            temp=numbers[i];
        }
    }
    System.out.println(temp + " " + count);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.