如何将唯一输入的值输入数组

时间:2019-09-23 00:16:49

标签: java

我的作业问题是创建一个名为NoDuplicates的过程,该过程将提示用户输入7个唯一整数。用户输入数字时,要求他们重新输入一个数字(如果先前已输入过)。输出7个唯一数字。

我尝试了while和for循环的许多不同组合,但是没有用

Traceback (most recent call last):
  File "mvce.py", line 18, in <module>
    countColors([Color.RED, Color.RED, Color.BLUE, Color.GREEN])
  File "mvce.py", line 16, in countColors
    allColors[c] += 1
KeyError: <Color.RED: 'cherry'>

2 个答案:

答案 0 :(得分:-1)

尝试使用Collection.contains的此逻辑,然后将其添加到collection中。它将从控制台询问用户的输入,并检查数据存储在列表中还是不在列表中。像这样,它将向用户询问使用的列表上7个唯一时间的值

public void uniqueDataCheckOnConsoleOnLimitByList() {
        int capacity = 7;
        List<String> dataList = new ArrayList<>(capacity);

        while (capacity != 0) {
            System.out.println("Please enter a number");
            Scanner in = new Scanner(System.in);

            String s = in.nextLine();
            if (dataList.contains(s)) {
                System.out.println("You already entered the number:" + s);
                //System.out.println("Please Enter a New Number"); 
            } else {

                dataList.add(s);
                capacity--;
            }
        }

    }

因为我没有检查Array的要求。请检查是否为数组。

public void uniqueDataCheckOnConsoleOnLimitByArray() {
        int capacity = 7;
        String data[]= new String[capacity];


        while (capacity != 0) {
            System.out.println("Please enter a number");
            Scanner in = new Scanner(System.in);

            String s = in.nextLine();

            if (containsArray(data, s)) {
                System.out.println("You already entered the number:" + s);
                //System.out.println("Please Enter a New Number"); 
            } else {

                data[capacity-1]=s;
                capacity--;
            }
        }



    }

    public boolean containsArray(String data[],String input){
        for(String s:data){
           if(input.equalsIgnoreCase(s))
               return true;
        }
        return false;
    }

答案 1 :(得分:-1)

我不理解您的代码,但是:

final int N = 7; // Constant, used multiple times throughout the program
Scanner sc = new Scanner (System.in);
int[] noDuplicates = new int[N];
noDuplicates[0] = sc.nextInt();
for(int i=1; i<N; i++){ // Loops through the array to put numbers in
    int query = sc.nextInt(); // Number to be put into the array
    for(int j=0; j<i-1; j++){
        if(noDuplicates[j] == query){ // If they are the same
            i--;
            continue; // Tells them to input a new number, skips all code ahead
        }
    }
    noDuplicates[i] = query;
}