Reputation: 359
I've just started learning Java (I am a C#.NET programmer as well). I am trying to get multiple user inputs and add them to an array. After this, I calculate the average from the given values.
For some reason, BlueJ will try to run my Java program forever. Meaning, It will keep showing the progress bar and will not open any console window.
I'm not sure if it's something wrong with my code, or BlueJ, because I've never encountered a problem such as this one before.
Here is my code:
import java.util.Scanner;
public class Problem22 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int inputs = 2;
int[] values = new int[3];
while (inputs > -1) {
values[inputs] = scanner.nextInt();
inputs--;
}
System.out.println(averageValue(values));
}
private static int averageValue(int[] values) {
int sum = 0;
for (int i : values) {
sum += i;
}
return (sum / values.length);
}
}
Please help me try and find a solution.
Upvotes: 2
Views: 8679
Reputation: 1
Terminal window opens only when there is an output. Th program has asked only for input. Therefore it is terminal window isn't opening. Replace your snippet by this one:
`while (inputs > -1)
{
System.out.println("Input number - "+inputs);
values[inputs] = scanner.nextInt();
inputs--;
}`
I hope you will see the terminal window.
Upvotes: 0
Reputation: 474
Your code worked for me in Eclipse, but I had to realize what I was supposed to do, enter three ints.
It is generally better to prompt the user for input. This may be a bug in BlueJ, but it's not too bad to have to output a prompt before asking for input. It's just generally a good thing to do.
Link to my version of the code with prompts:
https://gist.github.com/kaydell/6552282
I believe that the only reason not to prompt for input is if you are reading input from a file or something. When your program is interactive with the user, your programs should prompt the user for input.
Upvotes: 1
Reputation: 359
It seems that in BlueJ, you have to supply output before you ask for input. It's quite a weird bug.
More info:
http://www.bluej.org/help/faq.html#hangoninput
Upvotes: 4
Reputation: 45715
The code compiles just fine for me in IntelliJ IDEA, and also runs fine. so I would assume it's a BlueJ bug.
Here is an example input and output after running it (pressing enter after each input line)
3
4
5
4
(which means by the way your code works correctly, 4 is the average of 3,4,5...)
Which version of BlueJ are you using? I assume restart to BlueJ or even your machine didn't work?
Upvotes: 0