线性搜索多个整数

问题描述 投票:0回答:2

我正在尝试对整数数组进行线性搜索,如果整数是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;
    }
}
java algorithm search linear-search
2个回答
1
投票

如果算法发现3的倍数,则可以使用boolean found = false并将其设置为true。在for循环之后,您可以询问结果。


0
投票
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);
}

0
投票
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");
   }
  }``
© www.soinside.com 2019 - 2024. All rights reserved.