1

The assignment is to use a a While loop to take the first and last numbers and to find the average of the numbers in between. I have the code typed out and I think it works mathematically but I keep on getting an error when I'm trying to display the answer ("Answer is" + average), it keeps on saying that the Average hasn't been Initialized.

public static void whileLoop()      
{

int smallNumber = Integer.parseInt(JOptionPane.showInputDialog("Enter the smallest number:"));

int largeNumber = Integer.parseInt(JOptionPane.showInputDialog("Enter the largest number:"));

int counter = smallNumber;

int average;

int total = 0;

int numberCounter = 0;

        while (smallNumber <= largeNumber)
        {

            total = counter + total;
            counter = counter + 1;
            numberCounter++;
            average = total / numberCounter;

        }
        JOptionPane.showMessageDialog(null, "Answer is: " + average);
}
nem035
  • 34,790
  • 6
  • 87
  • 99
  • Try `int average = 0;` instead of `int average;` – s16h Sep 22 '14 at 23:04
  • No loop is necessary. Teacher has obviously never heard of Gauss. – user207421 Sep 22 '14 at 23:11
  • not related to the question but you'll run either into an endless loop, since small will always be less/equal than large or you'll never enter teh loop when small is greater than large. in addition, you don't need to calculate the average with every step and one of your counters is overhead – Christian R. Sep 22 '14 at 23:14
  • How do you recommend that I fix this then? I'm new to Java and I'm completely lost about how to approach this. – user3552805 Sep 22 '14 at 23:17
  • For the record, my non-looping answer: `return (first+last)/2;` – user207421 Sep 23 '14 at 03:29

4 Answers4

3

You have to initialize the average variable

The reason is that, in case you never enter the while loop, how is the program supposed to know what to print?

For example, you can initialize it to 0 but maybe a better solution would be to put some error-representing value like:

int average = Integer.MIN_VALUE;

Then if the program prints –2147483648 (Integer.MIN_VALUE) you know something went wrong.

Right now, your code logic is actually wrong as well. There is an improvement you can make to make the code simpler and correct:

The problem statement is to calculate:

(sum of all numbers) / (amount of numbers)

So you don't have to calculate the average each time around the loop. You can calculate it by dividing the total, which is the sum of all number with numberCounter, which is the amount of numbers, after the loop is finished.

Furthermore, you loop is actually an infinite loop because you never increment the smallNumber value so your loop condition smallNumber <= largeNumber will always be true. You instead increment counter which is incorrect.

This is how your loop should look like:

// ...

while(counter <= largeNumber) {  // use counter here instead of smallNumber
    total = counter + total;
    counter = counter + 1;
    numberCounter++;
}

// calculate average here
average = total / numberCounter;

// ...

Note: You should probably use double as the type for the average variable because the result would be much more exact this way. You only have to make two changes to do that:

// ...

double average = Double.NaN; // NaN means not a number

// ...

average = (double) total / numberCounter;

// ...

Also, since you are calculating the average outside the while loop, you no longer have to initialize it but you should still do it because it is good practice.

nem035
  • 34,790
  • 6
  • 87
  • 99
  • I tried that but it seems that I'm stuck in an infinite loop. Is there something in my code that's causing that? – user3552805 Sep 22 '14 at 23:16
  • I tried the counter <= largerNumber and it worked for me, but I couldn't get the formatting down. Logged back on here and saw your comment and you just saved my life. Thanks a bunch! – user3552805 Sep 22 '14 at 23:36
0

The error is Variable May not Have Been Initialized

While, for us humans, it is apparent that smallNumber is less than or equal to largeNumber at least once when used as intended, the compiler won't know that. If we bypass the entire while loop, theoretically, average will not have had a value assigned to it since it was declared.

Assigning an initial value of 0 will stop the error from occurring.

int average = 0;

Community
  • 1
  • 1
Compass
  • 5,867
  • 4
  • 30
  • 42
0

Instead of int average;, you need to have something like int average = 0;. This is because:

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

s16h
  • 4,647
  • 1
  • 21
  • 33
0

it keeps on saying that the Average hasn't been Initialized

Well, in like

int average;

you declared average variable, but you didn't initialize it (local variables are not initialized with default values). Compiler can't assume that condition in your loop will be evaluated as true at runtime at leas once to initialize average with total / numberCounter so you need to do it manually, like

int average = -1; 

Also your while condition is based on variables which are not updated in loop, so if you enter this loop you will not leave it (you will end up with infinite loop). You should change your condition to be based on some variables which change inside loop. It seems that condition should look like

while (counter <= largeNumber) 

Also you shouldn't calculate average in each loop iteration, you can do it after it. Also since average is floating point number (not integer) it should be declared as double. So consider changing your code to something like

while (counter <= largeNumber) {

    total = counter + total;
    counter = counter + 1;
    numberCounter++;
}
double average = (double)total / numberCounter;

I cast total to double because otherwise result of dividing would be integer so for values like 3/2 it would return 1, not 1.5.

Anyway if you don't have to use loops there is simpler way to calculate avg: min + (max-min)/2

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • I noticed that. It's actually taking me on an infinite loop. I also have to use a while loop, so I can't use and if statement. Any recommendations? – user3552805 Sep 22 '14 at 23:15