繁体   English   中英

如何编写一个程序来在 Java 中查找 0 和 1?

[英]How do I write a program to find 0's and 1's in Java?

我希望它从键盘中获取 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);
}

}

由于您正在寻找特定字符,我建议您改用 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++;
            }

你可以使用这样的方法,

public void haszero(int numbers[])
{
      int position;
      for(position = 0; position < numbers.size; position++)
      {
          while(numbers[position] > 0)
          {
              if(numbers[position] % 10 == 0)
              system.out.print("0 at " position)

              number=number/10;
           }
      }
      
}

然后你可以使用与此相同的方法 1. 或者你也可以做这样的事情

for(int position = 0; position < array.size; position++)
{
     if (String.valueOf(array[position]).contains("0"))
     system.out.print("0 at " position);
}

我会提供的最有影响力的建议是:

将您的输入存储为stringchar[]而不是int[]

解决方法:创建一个集合(如列表或数组)来保存您的有效索引,并一次遍历输入一个字母,将有效索引添加到您的集合中,因为它们满足您的条件。 实现一个“PrettyPrint()”,将您的收藏转换为一个不错的输出。

我继续编写了一个使用 int 数组的编码解决方案。 这是我后来的一项测试的测试结果。

Type 10 values: 0 1 2 3 4 5 6 7 8 9
1 found number 1, at position 2
1 found number 0, at position 1
8 found others, at position 3 4 5 6 7 8 9 10

Type 10 values: 12 23 34 45 127 21 84 0 73 364
3 found number 1, at position 1 5 6
1 found number 0, at position 8
6 found others, at position 2 3 4 7 9 10

Type 10 values: 

要退出程序,您只需按 Enter 键。

我的过程是维护三个 int 数组。 一个保存着所有的索引。 一个持有所有零的索引。 一个保存所有其他值的索引。

我一步一步地编写了这段代码,一路测试了每一步。 我可能运行了两三打测试,每一次测试代码的一小部分。

我做的第一件事是让输入循环正常工作。 我没有测试非数字输入,但可以轻松添加该测试。 我也没有将输入限制为 10 个数字。 如果需要,您可以输入 15 或 20 个数字。 最后,我没有将输入限制为两位数。 查找数字的代码应该适用于任何正整数值。

接下来,我编写了一个方法来确定一个数字是否包含特定数字。 该方法适用于任何数字,而不仅仅是零或一。

在那之后,就是让输出看起来正确的问题。

这是完整的可运行代码。

import java.util.Scanner;

public class ZeroAndOne {

    public static void main(String[] args) {
        new ZeroAndOne().processInput();
    }
    
    public void processInput() {
        Scanner scanner = new Scanner(System.in);
        String line;
        
        do {
            System.out.print("Type 10 values: ");
            line = scanner.nextLine().trim();
            String[] parts = line.split("\\s+");
            
            if (!line.isEmpty()) {
                int[] input = new int[parts.length];
                for (int index = 0; index < parts.length; index++) {
                    input[index] = Integer.valueOf(parts[index]);
                }
                
                System.out.println(processArray(input));
            }
        } while (!line.isEmpty());
        
        scanner.close();
    }
    
    private String processArray(int[] input) {
        int[] zeros = new int[input.length];
        int[] ones = new int[input.length];
        int[] other = new int[input.length];
        
        int zeroIndex = 0;
        int oneIndex = 0;
        int otherIndex = 0;
        
        for (int index = 0; index < input.length; index++) {
            boolean isOther = true;
            
            if (isDigit(input[index], 0)) {
                zeros[zeroIndex++] = index;
                isOther = false;
            }
            
            if (isDigit(input[index], 1)) {
                ones[oneIndex++] = index;
                isOther = false;
            }
            
            if (isOther) {
                other[otherIndex++] = index;
            }
        }
        
        StringBuilder builder = new StringBuilder();
        builder.append(oneIndex);
        builder.append(" found number 1, at position ");
        builder.append(appendIndexes(ones, oneIndex));
        builder.append(System.lineSeparator());
        
        builder.append(zeroIndex);
        builder.append(" found number 0, at position ");
        builder.append(appendIndexes(zeros, zeroIndex));
        builder.append(System.lineSeparator());
        
        builder.append(otherIndex);
        builder.append(" found others, at position ");
        builder.append(appendIndexes(other, otherIndex));
        builder.append(System.lineSeparator());
        
        return builder.toString();
    }
    
    private boolean isDigit(int value, int digit) {
        if (value == 0 && digit == 0) {
            return true;
        }
        
        while (value > 0) {
            int temp = value / 10;
            int remainder = value % 10;
            if (remainder == digit) {
                return true;
            }
            value = temp;
        }
        
        return false;
    }
    
    private StringBuilder appendIndexes(int[] array, int length) {
        StringBuilder builder = new StringBuilder();
        for (int index = 0; index < length; index++) {
            builder.append(array[index] + 1);
            if (index < (length - 1)) {
                builder.append(" ");
            }
        }
        
        return builder;
    }

}

假设您的输入是一行包含以空格分隔的整数,您可以读取它们,然后通过以下方式循环String项:

String input = Sc.readLine().split(" ");
int positions[] = new int[input.length];
int zeros = 0;
String zeroString = "";
int ones = 0;
String oneString = "";
int others = 0;
String otherString = "";
for (String item : input) {
    boolean isOther = true;
    String appendix = " " + item;
    if (item.indexOf("0") >= 0) {
        isOther = false;
        zeros++;
        zeroString += appendix;
    }
    if (item.indexOf("1") >= 0) {
        isOther = false;
        ones++;
        oneString += appendix;
    }
    if (isOther) {
        others++;
        otherString += appendix;
    }
}
System.out.println(ones + " found number 1, at position " + oneString);
System.out.println(zeros + " found number 0, at position " + zeroString);
System.out.println(others + " found others, at position " + otherString);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM