To work you could only print after performing all the accounting. To do this, you would need to save everything you counted and then just print the variable that stored those accounts. A possible solution would be to adjust your code to the following:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[4];
List<Integer> numerosJaContabilizados = new ArrayList<Integer>();
Map<Integer, Integer> numeroRepeticoes = new HashMap<Integer, Integer>();
int a;
for (int i = 0; i < array.length; i++) {
System.out.println("Digite um numero: ");
a = scan.nextInt();
array[i] = a;
}
System.out.println("Seu array ficou: " + Arrays.toString(array));
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j] && i != j && !numerosJaContabilizados.contains(array[i])) {
registrarNumeroRepeticao(array[i], numeroRepeticoes);
}
}
numerosJaContabilizados.add(array[i]);
}
for (Entry<Integer, Integer> numeroRepeticao : numeroRepeticoes.entrySet()) {
System.out.println(
"O numero " + numeroRepeticao.getKey() + " é repetido " + numeroRepeticao.getValue() + " vezes.");
}
}
private static void registrarNumeroRepeticao(int numero, Map<Integer, Integer> numeroRepeticoes) {
if (numeroRepeticoes.get(numero) != null)
numeroRepeticoes.put(numero, numeroRepeticoes.get(numero) + 1);
else
numeroRepeticoes.put(numero, 2);
}
The changes made:
- Added a variable to store repetitions of numbers: numeroRepeticoes. Notice that it is a map because there you can use as key the number and as value the repetitions.
- Added a variable to account for the numbers already processed: Computerized numbers. Your print while would be more or less for this, but the logic would break if the repeated number did not come in sequential order. For this it is best to use a variable that stores these accounts and is used to check whether the number should be accounted for or not.
- Added printing of values OUT of loops. So you will print the result only after processing everything.
That was an example of how your method would work, but here are some suggestions:
- Refactor the method: Your main method has many responsibilities, the ideal was to divide them at least among different methods. For example, one responsibility could be the reading of the data, the other would be the counting of repetitions and the other would be the printing of repetitions. It is an interesting exercise to try to modularize to the maximum one method. I recommend ;)
- Use the Collections API: I saw that you use arrays with primitive types but then you lose the power that the Collections API gives you! Even using it you would solve your problem in a few lines of code, but then it would not be very didactic so it is better to try to implement the logic from scratch same.
I hope I’ve helped ^^
Kind of confusing to understand. Try to post what would be the output of your algorithm here to facilitate understanding.
– viana