Java Array search unsorted array for a value using for each loop

Question

We have an unsorted array and we need to search it for a value.

If the value is found display 'value found', otherwise display 'not found'.

Code structure

// Search an array using for-each style for.  
public class Main {  
  public static void main(String args[]) {  
    int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 }; 
    int val = 5;  
    boolean found = false;  
    /*www.  j av a  2  s  .  c  om*/
    //your code here 
  
    if(found) {
      System.out.println("Value found!");  
    }else{
      System.out.println("Not found!");  
    }
    
  }  
}



// Search an array using for-each style for.  
public class Main {  
  public static void main(String args[]) {  
    int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 }; 
    int val = 5;  
    boolean found = false;  
 
    // use for-each style for to search nums for val  
    for(int x : nums) {  
      if(x == val) {  
        found = true;  
        break;  
      }  
    }  
  
    if(found) {
      System.out.println("Value found!");  
    }else{
      System.out.println("Not found!");  
    }
    
  }  
}



PreviousNext

Related