I'm new to programing and trying to solve this problem, but have no idea where I did it wrong.
Program is supposed to take user input until 0 is entered and after that, print out information of occurences of numbers user input - and here is my problem.
Program I wrote shows occurences of all numbers (up to max number that can be input), not only those that user wrote.
My code:
package numbers;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] occurences = new int[11];
int num = scan.nextInt();
while (num > 0 && num <= 11) {
occurences[num] ;
num = scan.nextInt();
}
for (int i = 0; i < 11; i ) {
System.out.print("Value: " i " Occurences: " occurences[i] " ");
}
}
}
CodePudding user response:
Use if
statement to print only numbers with occurences higher than 0.
Side notes:
- Array values initialization is not needed:
for (int i = 0; i < 11; i ) {
occurences[i] = 0;
}
Value at each index is already 0, check this question.
- While loop condition, does not make much sense
while (num > 0 && num <= 11) {
occurences[num] ;
num = scan.nextInt();
}
Array size is 11, meaning indexes range from 0 to 10 inclusive. Since you allow input 11, you will get ArrayIndexOutOfBoundsException.
CodePudding user response:
if the occurrence is = 0 don't print it.