Array question in java?

I had a problem statement that said input any # of #’s and compute the frequency of each number. This was later modified a bit to be grades, and the array was supposed to be out of representing the grades. so far i have this:

public class ArrayandSwitch

{

public static void main(String[] args)

{

int frequency[] = new int[];

int number;

int grade = ;

Scanner scan = new Scanner(System.in);

System.out.println(“How many numbers are you inputing?”);

number = scan.nextInt();

System.out.println(number);

for(int i = ; i < number; i++)

{

System.out.print(“Enter number ” + (i + ) + “: “);

grade = scan.nextInt();

frequency[grade]++;

}

for(int i = ; i < number; i++)

{

System.out.println(grade + “t” + frequency[grade] + “n”);

}

}

}

My problem is that i can’t display the grade and the frequency(number of times it occurs) because all that will be stored in the grade is the last number entered. I could do this if i made another array but my teacher was clear to not do that. I could also do it if i put the message in the first loop where it displays after every entry but thats also not right. I don’t see how this is possible without using another array for the grades. Anyone have any ideas?

Answer
🥇 Favorite Answer

  • You just needed to reform your bottom for loop:

    for(int i = ; i < number; i++)

    {

    System.out.println(grade + “t” + frequency[grade] + “n”);

    }

    Should be :

    for(int i = ; i < frequency.length; i++)

    {

    if(frequency[i] != )

    System.out.println(i + “t” + frequency[i] + “n”);

    }

  • See also  How can I get a program to factor polynomials on my TI-84 Plus calculator?

    Leave a Comment