이것은 내가 원하는 것입니다 :
숫자가 아닌 숫자가 입력 될 때까지 사용자가 원하는만큼 많은 숫자를 입력하도록하십시오. 은 100 개 미만의 숫자가 있다고 가정합니다. 자주 입력하는 번호를 찾습니다. ( 경우 모두 인쇄, 하나 이상 존재한다.)
출력 예 :
입력 : 5
입력 4
입력 9
입력 9
입력 4
입력 1
입력 : a
가장 일반적인 : 4, 9
나는 가장 흔한 숫자 인 것을 알아낼 수있는 지점에 있습니다. 그러나 같은 번호를 반복해서 인쇄하고 싶지는 않습니다. 위의 예 : 가장 일반적인 방법 : 4, 9, 9, 4
수행해야 할 작업은 무엇입니까?같은 번호의 반복을 피하려면 어떻게해야합니까?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[100];
System.out.print("Input: ");
input[0] = in.readLine();
int size = 0;
for (int i = 1; i < 100 && isNumeric(input[i-1]); i++) {
System.out.print("Input: ");
input[i] = in.readLine();
size = size + 1;
}
/*for (int i = 0; i < size; i++) { //testing
System.out.println(input[i]);
}*/
int numOccur;
int[] occur = new int[size];
for(int i = 0; i < size; i++) {
numOccur = 0;
for (int j = 0; j < size; j++) {
if(input[i].equals(input[j])) {
numOccur = numOccur + 1;
}
}
occur[i] = numOccur;
//System.out.println(numOccur); //testing
}
int maxOccur = 0;
for(int i = 0; i < size; i++) {
if(occur[i] > maxOccur) {
maxOccur = occur[i];
}
}
//System.out.println(maxOccur); //testing
for (int i = 0; i < size && !numFound; i++) {
if(occur[i] == maxOccur) {
System.out.println(input[i]);
}
}
}
//checks if s is an in, true if it is an int
public static boolean isNumeric (String s) {
try {
Integer.parseInt(s);
return true; //parse was successful
} catch (NumberFormatException nfe) {
return false;
}
}
해결책을 찾았습니다!
String[] mostCommon = new String[size];
int numMostCommon = 0;
boolean numFound = false;
for (int i = 0; i < size; i++) {
int isDifferent = 0;
if (occur[i] == maxOccur) {
for (int j = 0; j < size; j++) {
if (!(input[i].equals(mostCommon[j]))) {
isDifferent = isDifferent + 1;
}
}
if (isDifferent == size) {
mostCommon[numMostCommon] = input[i];
numMostCommon = numMostCommon + 1;
}
}
}
for (int i = 0; i < numMostCommon - 1; i++) {
System.out.print("Most common: " + mostCommon[i] + ", ");
}
System.out.println(mostCommon[numMostCommon - 1]);
이 숙제가 있습니까? –
yeap, 죄송합니다 태그를 추가하는 것을 잊어 버렸습니다. & while 루프에 대해서만 함수, 배열을 배웠습니다 – user1215225