帮助我找到此代码中的错误,我不明白为什么它不起作用。我想显示数组中的所有唯一数字,以及它们的频率(它们出现的次数)。
package myProj;
import java.util.Scanner;
public class Freq {
static boolean isRepeated(int[] temp,int zz){
int flag=0;
int l=java.util.Arrays.asList(temp).indexOf(zz);
for(int p=0;p<l;p++){
if(temp[p]==zz){
flag=flag+1;
}
}
if(flag==0){
return false;
}
else{
return true;
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the no of array elements");
int numOfNumbers = sc.nextInt();
int arrayOfNumbers[] = new int[numOfNumbers];
for (int i = 0; i < numOfNumbers; i++) {
System.out.print("Enter the number:");
arrayOfNumbers[i] =sc.nextInt();
}
for(int i = 0; i<numOfNumbers; i++){
int z=arrayOfNumbers[i];
if(!(isRepeated(arrayOfNumbers,z))){
int count=0;
for(int j=0;j<numOfNumbers;j++){
if(arrayOfNumbers[j]==arrayOfNumbers[i]){
count=count+1;
}
else{
continue;
}
}
System.out.println("Frequency of "+arrayOfNumbers[i]+"is"+count);
}
else{
continue;
}
}
}
}
[2,20,11,10,5,14,47,23,20,12,11,10]的预期输出示例
请帮助纠正我的代码,而不是提出新的逻辑。
答案 0 :(得分:0)
你可以让它变得更容易:
public class Freq {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the no of array elements");
int numOfNumbers = sc.nextInt();
Integer[] arrayOfNumbers = new Integer[numOfNumbers];
for (int i = 0; i < numOfNumbers; i++) {
System.out.print("Enter the number:");
arrayOfNumbers[i] = sc.nextInt();
}
// to remember for what numbers we already count freq
List<Integer> tmpList = new ArrayList<>(numOfNumbers);
for (Integer number : arrayOfNumbers) {
if (!tmpList.contains(number)) {
tmpList.add(number);
System.out.println("Frequency of " + number + " is " + Collections.frequency(Arrays.asList(arrayOfNumbers), number));
}
}
}
}