Reputation: 15
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
Upvotes: 0
Views: 371
Reputation: 1121
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);
}
Upvotes: 1