我正在尝试对整数数组进行线性搜索,如果整数是3的倍数,它将打印数组中数字的索引,如果没有数字是整数的3的倍数返回-1我试图在不使用方法的情况下实现这一点,我的问题是我将如何执行-1的打印/返回?知道我的代码是
int[] a = {3, 5, 22, 7, 9, 8, 21};
System.out.println("the index of 3 multiplies is" );
for (int i = 0; i < a.length; i++) {
if (a[i] % 3 == 0) {
System.out.print(i + " ");
continue;
}
}
如果算法发现3的倍数,则可以使用boolean found = false
并将其设置为true
。在for循环之后,您可以询问结果。
int[] a = {3, 5, 22, 7, 9, 8, 21};
int multipleOfThree = 0;
System.out.println("the index of 3 multiplies is" );
for (int i = 0; i < a.length; i++) {
if (a[i] % 3 == 0) {
System.out.print(i + " ");
multipleOfThree++;
}
}
if( multipleOfThree == 0 ){
System.out.println(-1);
}
int[] a = {1,5,22,7,52,8,20};
System.out.println("the index of 3 multiplies is" );
boolean found = false;
for(int i = 0; i<a.length;i++){
if(a[i]%3==0){
found = true;
System.out.println(i+" ");
}
}
if(!found){
System.out.println("-1");
}
}``