我可以看到列表中包含的两个或多个相同数字的结果。一切都必须基于列表,代码本身很简单但我不知道如何实现相同的值打印屏幕。
所有这些都是在列表中输入的5个数字下完成的。
示例:
介绍1 - 2 - 3 - 3 - 4
输出将是重复的数字3。
这是我的代码:
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: ");
}
}
非常感谢你!
答案 0 :(得分:2)
有许多不同的方法可以解决这个问题。我首先想到的是对ArrayList进行排序并检查相邻的字符。
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) + " ");
}
}
}