I'm writing a code for how many times the numbers I've entered, but I don't know how to sort them in ascending order Array.sort(arr); <- This code doesn't align wherever I put 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];
int[] count = new int[input];
int[] a = new int[input];
int[] b = new int[1];
int distinctCount = 0;
boolean found = false;
for (int i = 0; i < input; i++) {
found = false;
numbers[i] = sc.nextInt();
for (int j = 0; j <= distinctCount; j++) {
if (b[j] == numbers[i]) {
count[j] = count[j] + 1;
found = true;
break;
}
}
if (!found) {
a[distinctCount] = numbers[i];
count[distinctCount] = 1;
distinctCount++;
b = Arrays.copyOf(a, distinctCount + 1);
}
}
for (int k = 0; k < distinctCount; k++)
System.out.println(b[k]+" "+count[k]);
}
}
For example, to put in six numbers, Enter 6 (Enter) 1 (Enter) 1 (Enter) 1 (Enter) -1 (Enter) 2 (Enter) 3 (Enter)
Output is: -11 (Enter) One, three. (Enter) 21 (Enter) I'd like to print it out in 31 (Enter) format. Please help me!
java
How to sort by array elements.
-> import java.util.*
-> int[] numbers = new int[]{4, 7, 2, 5, 1};
-> Arrays.sort(numbers)
-> numbers
| | Variable numbers of type int[] has value int[5] { 1, 2, 4, 5, 7 }
© 2024 OneMinuteCode. All rights reserved.