数组如何编写程序来查找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);
}
}
# 1 楼答案
我开始编写一个使用int数组的解决方案。这是我后来一次测试的结果
要退出程序,只需按回车键
我的过程是维护三个int数组。其中一个拥有所有的索引。其中一个包含所有零的索引。其中一个包含所有其他值的索引
我一步一步地编写了这段代码,一路测试每一步。我可能运行了两三打测试,每个测试只测试代码的一小部分
我做的第一件事就是让输入循环正常工作。我没有测试非数字输入,但该测试可以轻松添加。我也没有将输入限制为10个数字。如果你愿意,你可以输入15或20个数字。最后,我没有将输入限制为两位数。查找数字的代码应适用于任何正整数值
接下来,我编写了一个方法来确定一个数字是否包含特定的数字。该方法适用于任何数字,而不仅仅是0或1
之后,就是让输出看起来正确的问题
下面是完整的可运行代码
# 2 楼答案
你可以用这样的方法
然后你可以用同样的方法来计算1。 或者你也可以这样做
# 3 楼答案
假设您的输入是一行,其中包含以空格分隔的整数,您可以全部读取它们,然后通过以下方式循环
String
项: