자바 frequency 출력 문제입니다
조회수 916회
입력한 숫자들이 몇번 입력되었는지에 대한 코드를 짜고 있는데, 어떻게 하면 오름차순으로 정렬이 될지 감이 잘 잡히지 않네요, Array.sort(arr); <- 이 코드는 어디에 넣어도 정렬이 되지 않네요.
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]);
}
}
예를 들어 6가지의 숫자를 넣기 위해, 6 (엔터)을 입력하고 1 (엔터) 1 (엔터) 1 (엔터) -1 (엔터) 2 (엔터) 3 (엔터)
output은: -1 1 (엔터) 1 3 (엔터) 2 1 (엔터) 3 1 (엔터) 형식으로 출력하고 싶습니다. 도움 부탁드려요!
댓글 입력