[英]How to create a empty set of array and fill it with user input and print it out?
Here is my code to fill an empty array : 这是我填充空数组的代码:
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);
}
}
That is my code because I want to have this output. 这是我的代码,因为我想要这个输出。 I need to stack input numbers in array and print it out like this. 我需要在数组中堆叠输入数字并将其打印出来。
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
I would suggest using LinkedHashSet
我建议使用LinkedHashSet
because 因为
Here is an example: 这是一个例子:
Set<Integer> numbers = new LinkedHashSet<>();
while(/*some logic to exit on special input*/) {
if(!numbers.add(userInputNum){
// number was already present
}
}
If you don't want to use LinkedHashSet or fill method in array this is an alternate way to do it. 如果您不想在数组中使用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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.