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
numbers[a] += a;ifa == -1numbers[-1]will not worknumbers[a] += a;what happened toi? and why are you using addition? and where is the sort?insertinto the array at theindexwhere theindexis thenumber inputtednumbers[i] = a;and then he can get on with sorting. What do you make ofSystem.out.println(i + " " + numbers[i] / i);though?cheat