首页 > 解决方案 > 如何编写一个程序来在 Java 中查找 0 和 1?

问题描述

我希望它从键盘中获取 10 个值,并找出 10 个输入中的任何一个是否包含 0 或 1,如果是,那么数组中的位置是什么?

example

 Input = 9 15 91 1 0 22 31 67 88 33

output = 4 found number 1, at position 2 3 4 7
         1 found number 0, at position 5
         5 found others, at position 1 6 8 9 10

我不能再写了,因为我还是不明白。请告诉我我试图写它,但输出仍然不正确。

public static int SequentialSearch(int number[], int key_1, int key_0) {
    int looker;

    for (looker = 0; looker < number.length; looker++) {
        if (number[looker] == key_1)
            return looker;
        if (number[looker] == key_0)
            return looker;
    }
    return -1;
}

public static void Loopcheck(int number[]) {
    int key_1, key_0, others_key;

    for (int count_check = 0; count_check < number.length; count_check++) {
        if (number[count_check] / 10 == 1 || number[count_check] % 10 == 1) {
            key_1 = 1;
            break;
        } else if (number[count_check] / 10 == 0 || number[count_check] % 10 == 0) {
            key_0 = 0;
            break;
        }

    }

}

public static int Print(int number[], int location) {
    for (int loop = 0; loop < number.length; loop++)
        if (location > -1)
            System.out.print(" 0 : " + location);
    return 0;
}

public static void main(String[] args) {
    Scanner Sc = new Scanner(System.in);
    int value1, value0, location, key1;
    int[] number = new int[10];
    for (int count = 0; count < number.length; count++) {
        number[count] = Sc.nextInt();
    }
    int item1 = 1;
    int item0 = 0;
    location = SequentialSearch(number, item1, item0);
    Loopcheck(number);
    Print(number, item1);
}

}

标签: javaarrays

解决方案


由于您正在寻找特定字符,因此我建议您改用 String 或 char 数组。您可以考虑的一些代码可能会让您了解如何解决问题:

//part 1
            Scanner sc= new Scanner(System.in);    //System.in is a standard input stream
            System.out.print("Enter first number- ");
            int a= sc.nextInt();
            System.out.print("Enter second number- ");
            int b= sc.nextInt();
            System.out.print("Enter third number- ");
            int c= sc.nextInt();
// part 2
                String Input = String.join(" ",Integer.toString(a),Integer.toString(b),Integer.toString(c));
                System.out.println(Input);
// part 3
            int i = 0;

            while(i<Input.length()){
            if(Input.charAt(i)=='0') System.out.println(String.join(" ","0 at position",Integer.toString(i+1)));
            if(Input.charAt(i)=='1') System.out.println(String.join(" ","1 at position",Integer.toString(i+1)));
            i++;
            }

推荐阅读