关于遍历数组时for循环中的“else”语句

时间:2014-01-21 09:46:41

标签: java for-loop traversal

我正在尝试解决一个问题,我需要找到所有偶数。我需要输入5个数字,如果没有数字,我想打印数组中找不到偶数。 所以我的问题是当我遍历for循环时,我的代码打印偶数在数组中找不到。它打印每个非偶数,这显然不是它的假设。我需要某种暗示。这不是家庭作业btw,这是在Programmr.com上发现的问题。这是我的代码:

 import java.util.Scanner;

 public class ArrayEven {

   public static void main(String args[]) {
     @SuppressWarnings("resource")
     Scanner scanner = new Scanner(System.in);
     int x, arr[] = new int[5];

     for (int i = 0; i < arr.length; i++) {
       arr[i] = scanner.nextInt();
       if (i == 4)
         break;

    }

     for (int i = 0; i < arr.length; i++) {

       x = arr[i] % 2;

       if (x == 0) {

         System.out.println(arr[i]);

       }

       else if (x != 0) {  //this is obviously wrong. Do I need another for-loop for this?

         System.out.println("Even number not found in array.");

       }

     }

   }

 }

2 个答案:

答案 0 :(得分:3)

你可以在这里使用boolean, 使用boolean初始化false变量 如果您发现任何even,请将boolean设为true 并检查boolean条件中的if

示例:

boolean isAvailble = false;
...
// Some code
...
for (int i = 0; i < arr.length; i++) {
       x = arr[i] % 2;
       if (x == 0) {
         System.out.println(arr[i]);
         isAvailble = true;
       }
}

if (! isAvailable) {  
     System.out.println("Even number not found in array.");
}

答案 1 :(得分:1)

public static void main(String args[]) {
 @SuppressWarnings("resource")
 Scanner scanner = new Scanner(System.in);
 int x, arr[] = new int[5];

 for (int i = 0; i < arr.length; i++) {
   arr[i] = scanner.nextInt();
   if (i == 4)
     break;

}
boolean evenFound = false; 

 for (int i = 0; i < arr.length; i++) {

   x = arr[i] % 2;

   if (x == 0) {

     System.out.println(arr[i]);
     evenFound = true; 

   }

 }
 if(!evenFound){
     System.out.println("Not found");

  }

}