As I can do to get to see the result of two or more identical numbers contained in a list. Everything has to be based on lists, the code itself is simple but I have no idea how to achieve the same values print screen.
All this is done under 5 numbers entered in a list.
example:
Introduce 1 - 2 - 3 - 3 - 4
And the output would be the number 3 is repeated.
This is my code:
package generarlista;
import java.util.*;
public class GenerarLista {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int num;
Scanner read = new Scanner (System.in);
List<Integer> lista = new ArrayList<>();
System.out.println("A list of 5 integers is generated and printed equal values\n");
for (int i=1; i<6; i++){
System.out.println("Enter the value "+ i +" element to populate the list");
num = read.nextInt();
lista.add(num);
}
System.out.println("Data were loaded \n");
System.out.println("Values in the list are: ");
Iterator<Integer> nameIterator = lista.iterator();
while(nameIterator.hasNext()){
int item = nameIterator.next();
System.out.print(item+" / ");
}
System.out.println("\n");
System.out.println("Equals are: ");
}
}
thank you very much!
There are many different approaches that could solve this problem. This first thing that came to mind for me is to sort the ArrayList and check adjacent characters.
package generarlista;
import java.util.*;
public class GenerarLista {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int num;
Scanner read = new Scanner (System.in);
List<Integer> lista = new ArrayList<>();
System.out.println("A list of 5 integers is generated and printed equal values\n");
for (int i=1; i<6; i++){
System.out.println("Enter the value "+ i +" element to populate the list");
num = read.nextInt();
lista.add(num);
}
System.out.println("Data were loaded \n");
System.out.println("Values in the list are: ");
Collections.sort(lista);
List<Integer> duplicates = new ArrayList<>();
for (int i = 0; i < lista.size(); i++) {
System.out.print(lista.get(i) + " ");
if (i < lista.size()-1 && lista.get(i) == lista.get(i+1))
if (!duplicates.contains(lista.get(i))
duplicates.add(lista.get(i));
}
System.out.println("\n");
System.out.println("Equals are: ");
for (int i = 0; i < duplicates.size(); i++) {
System.out.print(duplicates.get(i) + " ");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With