'Java Calculating average from users input
I have a problem with my code.Please help me to solve it. Program should quit and return average when q is entered. If you enter 5 numbers it is working fine. The array size should be 20. Here is the code:
import java.util.Scanner;
public class test{
public static void main(String[] args){
int x;
int count=0;
char q= 'q';
Scanner input = new Scanner(System.in);
int[] array = new int[5];
System.out.print("You have entered 0 numbers, please enter a number or q to quit:" );
while (input.hasNextInt()){
for (int i = 0; i < array.length; i++)
{
array[i] = input.next();
count++;
System.out.print("You have entered " +count+ " numbers, please enter a number or q to quit:" );
}
}
System.out.println("Average is " + Average(array));
}
public static int Average(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++)
sum += array[i];
return sum / array.length;
}
}
Solution 1:[1]
Use List instead of array. Check if input is q print the average and return system.exit(0)
Solution 2:[2]
You should check input.hasNextInt() before each input.nextInt().
Solution 3:[3]
You're using a compound loop which is negating the ability to break out of the first/outter loop.
You should consolidate the two loops into a single loop, looking for two escape conditions, either the user presses q or they enter 5 numbers...
Because you're expecting mixed input, you need to convert the input manually to an int....
String line = null;
// Loop until count >= 5 or the user inputs "q"
while (count < array.length && !(line = input.nextLine()).equalsIgnoreCase("q")) {
try {
// Convert the input to an int...
int value = Integer.parseInt(line);
array[count] = value;
count++;
System.out.print("You have entered " + count + " array, please enter a number or q to quit:");
} catch (NumberFormatException exp) {
System.out.println(line + " is not an int value...");
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhijith Nagarajan |
| Solution 2 | Chen Pang |
| Solution 3 | MadProgrammer |
