Search for a number in an array java -


i have code first generates array 100 elements, places randomly generated numbers in each element. trying search number , if found, print out index. code have far is:

import java.util.scanner;  public class lab01  {      public static void main(string[] args)      {         int[] nums = new int[100];          (int = 0; < 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 search for?");      num = input.nextint();      boolean found = false;              (int = 0; < nums.length; i++)          {             if (num == nums[i])              {                              found = true;                break;             }              if (found)             {                 system.out.println("that number found @ index" + i);                 break;             }             else             {                 system.out.println("that number not found.");                 break;             }         }            } } 

i put in print statements see values, verify working, returns "not found". missing here?

try replace block, see explanation in bottom :

     (int = 0; < nums.length; i++)      {         if (num == nums[i])          {                          found = true;            break;         }          if (found)         {             system.out.println("that number found @ index" + i);             break;         }         else         {             system.out.println("that number not found.");             break;         } 

with:

 int i; // create  ( = 0; < nums.length; i++)  // , remove int loop     {         if (num == nums[i])          {                          found = true;            break;         }     }         if (found)         {             system.out.println("that number found @ index " + i);         }         else         {             system.out.println("that number not found.");         } 

explanation:
put out of for loop both if condtion , remove break statement them , create int = 0 before for loop above.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -