Hey everyone, I am writing a program that requires me to use an array to find the mode of 10 numbers. I have working except I want it to just print the mode, but it keeps printing every number I enter. Any suggestions? Thanks in advance.

import TerminalIO.KeyboardReader;
 public class mode
{
	public static void main(String[] args)
	{
	  KeyboardReader reader = new KeyboardReader();
	  double [] num = new double[10];
	  double [] mod = new double[10];
	  double number;
	  double mode;
		for(int i = 0; i < 10; i++)
		{
		  System.out.println("Please Enter Your Numbers: ");
		  number = reader.readDouble();
		  num[i] = number;
		}

		for(int a = 0; a < 10; a++)
		{
			for(int j = 0; j < 1000; j++)
			{
				if(num[a] == j)
			  	{
				  mode = num[a];
			  	  System.out.print(mode+" ");
				}
			}
		}
	}
}

Recommended Answers

All 5 Replies

It keeps printing every number you enter because the print statement is inside the loop where you enter numbers! Try splitting this into three stages, it's easier to think about things one at a time:
1. Get the 10 numbers from the user, saving them in the array
2. calculate the mode of the numbers in the array
3. print the answer

ps: There's no guarantee that a set of numbers have only 1 mode, so the problem statement may be a bit misleading.

The mode is not necessarily unique, since the same maximum frequency may be attained at different values. The most ambiguous case occurs in uniform distributions, wherein all values are equally likely.

http://en.wikipedia.org/wiki/Mode_%28statistics%29

I took my print line out of the loop and I am getting an error that says I never initialized variable mode

That's because you never initialised the variable mode.

It's declared but not initialised on line 10.
It's assigned a value on line 24, but that's inside an if test, so the compiler has no way of knowing if that statement will ever be executed.
Then you try to print it, but there is no guarantee that it will have a value (at least, as far as the compiler can tell).

If you simply initialise it the problem will go away.

where would you initialize the mode?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.