Levo muchos días dándole vueltas a como resolver el ejercicio. Alguna idea o pista que me ayude a resolverlo ??.
No quiero mirar la solución.
Actualmente tengo esto escrito de código, pero no es definitivo.
Ayuda porfavor.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Integer> numeros = new ArrayList<>();
for(int i = 0; i < 10; i++ ){
numeros.add(Integer.parseInt(reader.readLine()));
}
int contador = 0;
for(int i = 0; i < numeros.size(); i++){
for(int j = i + 1; j < numeros.size(); j++) {
if (numeros.get(i) == numeros.get(j)) {
contador++;
}
}
}
System.out.println("La secuencia más larga es de : " + contador);
}
M.A.P.M.
Nivel 8
Estoy un poco perdido. Ayuda
Resuelta
Comentarios (2)
- Populares
- Nuevas
- Antiguas
Debes iniciar sesión para dejar un comentario
Guadalupe Gagnon
29 enero, 15:15
#1 .equals() is how you compare Strings, not ==
#2 The task says to output a number. Whenever anything is output other than what the task says to output then you will fail. The output from this code includes "La secuencia más larga es de : " which will be an automatic fail.
#3 This code increases "contador" when the String at index i equals the String at index j. There are multiple problems with this logic because 1) the index j should not go through the rest of the list, it should stop as soon as a different item is located 2) "contador" keeps counting after a change in i but it should reset and start a new count each new loop cycle 3) "contador" doesn't count the initial value.
For testing purposes lets ignore the reading of 10 inputs and just fill "numeros" with our own testing values. Say you filled it with {3, 3} and ran the rest of the code; "contador" would output the value of 1 instead of the correct value of 2 because it only increased when i and j had equal values in the array and missed counting the initial value of i.
Lets say you had "numeros" filled with {4, 4, 4, 4}; "contador" would output 6 instead of the correct value of 4 because each new loop cycle of the 'i' loop "contador" continues increasing instead of resetting.
Finally if you had the value {4, 4, 1, 4, 4}; "contador" would output 6 instead of the correct value of 2 because it continues counting equal values even when they are not in a consecutive order.
+2
M.A.P.M.
29 enero, 15:14
Después de darle muchas vueltas y probar un montón de modificaciones en mi código, he conseguido resolverlo. Por si sirve de ayuda, ojo con el operador == y el método .equals(), ya que el primero compara referencias a objetos y el segundo compara el contenido del objeto.
0