这是我填充空数组的代码:
package duplicate.terminator;
import java.util.Arrays;
import java.util.Scanner;
public class DuplicateTerminator {
public static void main(String args []){
Scanner number = new Scanner(System.in);
int a, num;
int[] integerset = null;
System.out.println("Enter Number: ");
num = number.nextInt();
Arrays.fill(integerset, num);
}
}
那是我的代码,因为我希望有这个输出。 我需要在数组中堆叠输入数字并将其打印出来。
Sample Input/Output:
Enter number: 5
5
Enter number: 9
5 9
Enter number: 2
5 9 2
Enter number: 9
9 has already been entered
5 9 2
Enter number: 1
5 9 2 1
答案 0 :(得分:3)
我建议使用LinkedHashSet
因为
以下是一个例子:
Set<Integer> numbers = new LinkedHashSet<>();
while(/*some logic to exit on special input*/) {
if(!numbers.add(userInputNum){
// number was already present
}
}
答案 1 :(得分:0)
如果您不想在数组中使用LinkedHashSet或fill方法,这是另一种方法。
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int i, j;
int[] list = new int[10];
for (i = 0; i <= 9; i++)
{
System.out.println("Enter a number :");
list[i] = scan.nextInt();
for (j = 0; j < i; j++)
{
if (list[j] == list[i])
{
System.out.println(list[j] + " has already been entered");
i--;
}
}
for(j = 0; j <= i; j++)
{
System.out.print(list[j] + " ");
}
System.out.println();
}
}