Searching an array element one by one - Java Language Basics

Java examples for Language Basics:Array

Description

Searching an array element one by one

Demo Code

You could just use a for loop, like this:

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {

    int[] lotto = new int[6];

    for (int i = 0; i < 6; i++)
      lotto[i] = (int) (Math.random() * 100) + 1;
    /*from  w  w w  . j a v a  2  s .c o m*/
    Arrays.sort(lotto);
    
    int lucky = 13;
    int foundAt = -1;
    
    for (int i = 0; i < lotto.length; i++)
      if (lotto[i] == lucky)
        foundAt = i;

    if (foundAt > -1)
      System.out.println("My number came up!");
    else
      System.out.println("I'm not lucky today.");
  }

}

Related Tutorials