mercredi 27 janvier 2016

Search for a number in an array java

I have code that first generates the array with 100 elements, then places randomly generated numbers in each element. I am trying to do a search for a number and if found, print out its index. the code I have so far is:

import java.util.Scanner;

public class Lab01 
{

    public static void main(String[] args) 
    {
        int[] nums = new int[100];

        for (int i = 0; i < nums.length; i++)
        {
            nums[i] = (int)((Math.random() * 100) + 1);
            System.out.print(nums[i] + " , ");
        }
     System.out.println();
     Scanner input = new Scanner(System.in);
     int num;
     System.out.println("What number would you like to search for?");
     num = input.nextInt();
     boolean found = false;        
     for (int i = 0; i < nums.length; i++) 
        {
            if (num == nums[i]) 
            {              
               found = true;
               break;
            }

            if (found)
            {
                System.out.println("That number was found at index" + i);
                break;
            }
            else
            {
                System.out.println("That number was not found.");
                break;
            }
        }       
    }
}

I put in the print statements to see the values, so I could verify that it was working, but it ALWAYS returns "Not found". What am I missing here?




Aucun commentaire:

Enregistrer un commentaire