在数组中搜索值,如果不存在则存储它

时间:2016-11-27 00:29:17

标签: java arrays loops conditional

我希望将一个介于10和100之间的整数输入到一维数组中,如果该值已经存在于数组中的任何位置,请不要将其插入到数组中,而是通知用户并恢复输入直到5个唯一数字为添加。

这是我的代码。我知道它不对,但你可以看到我想要做的是使用简单的for循环和搜索方法来获取数字,将它们存储到数组中并搜索重复数据。我的代码中的问题是,我似乎无法将我刚刚输入的数字设置为变量' key'我需要发送到方法'搜索'。

// input an integer between 10 and 100, add to array and print results. if value is already in array, notify user, print array. keep adding to array until 5 unique values have been entered

import java.util.Scanner;

public class ArraySearch {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int[] list = new int[5];

        for (int i = 0; i < list.length; i++) {
            System.out.println("Enter number: ");
            list[i] = input.nextInt();
        }
        int count = search(list, key);
        System.out.println("It has been entered.");
    }

    public static int search(int[] list, int key) {

        int count = 0;
        for (int i = 0; i < list.length; i++) {
            if (list[i].equals(key)) {
                ;
            }
            count++;
        }
        return (count);
    }
}

2 个答案:

答案 0 :(得分:1)

数组的简单示例。可以使用备用数据结构列表集进行改进。

search()方法基本上包含在while()循环中,即for()循环示例搜索已经包含的目标号。

.answers在循环之前声明,并确保找到5个唯一数字。

getAllByQuestionId()

替代版本:

int c = 0;

另外,使用import java.util.Arrays; import java.util.Scanner; public class ArraySearch { public static void main(String[] args) { Scanner s = new Scanner(System.in); int[] list = new int[5]; int c = 0; System.out.println("Enter number: "); while (c < 5 && s.hasNext()) { int n = s.nextInt(); boolean has = n >= 10 && n <= 100; for (int i = 0; i <= c && !has; ++i) if (list[i] == n) has = true; if (!has) { System.out.println("It has been entered."); list[c++] = n; } } System.out.println("Result = " + Arrays.toString(list)); s.close(); } }

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class ArraySearch {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        Set<Integer> set = new HashSet<Integer>(5);
        int c = 0;
        System.out.println("Enter number: ");
        while (c < 5 && s.hasNext()) {
            int n = s.nextInt();
            if ((n < 10) || (n > 100) || !set.add(n))
                continue;
            else {
                System.out.println("It has been entered.");
                c++;
            }
        }
        System.out.println("Result = " + set);
        s.close();
    }
}

编辑:还添加了10-100规格

edit2:使用search()方法

的方法

答案 1 :(得分:0)

您将输入直接保存在数组中 将输入保存在时间变量中,您将传递给search。并根据search的结果添加到数组或提示另一个输入。

int[] list = new int[5];

for (int i = 0; i < list.length; i++) {
    System.out.println("Enter number: ");
    int temp = input.nextInt();
    if(search(list,temp) == 0)
        list[i] = temp;
    }else{
        System.out.println("It has been entered.");
        i--;
    }
}
相关问题