Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: How do you find the the exact index of an element that matches a search in an array?

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default How do you find the the exact index of an element that matches a search in an array?

    import java.util.*;
    public class ArrayTest {
        public static void main (String[]args) {
            Scanner input = new Scanner(System.in);
            int [] number = new int[5];
     
      System.out.println("Enter 5 numbers");
      for (int i=0; i<number.length;i++) {
            number[i] = input.nextInt();
     
        }
      }
        }
    lets say i enter 4,6,70,12,5
    I want to search for 70 (using a loop of course), and when i find it, i want to display the index it is in.in this case 2


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: How do you find the the exact index of an element that matches a search in an array?

    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: How do you find the the exact index of an element that matches a search in an array?

    Iterate over the array and compare each element to the target. When you get a match you have found the index. This is best achieved using a method that can return the index as soon as it is found or some other default value (-1) if it is not found.
    Improving the world one idiot at a time!

  4. The Following User Says Thank You to Junky For This Useful Post:

    ojonugwa (August 23rd, 2013)

  5. #4
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default Re: How do you find the the exact index of an element that matches a search in an array?

    This is what i eventually did
    import java.util.*;
    public class ArrayTest {
        public static void main (String[]args) {
            Scanner input = new Scanner(System.in);
            int [] number = new int[5];
            int index =0;
            int numToSearchFor = 50;
      System.out.println("Enter 5 numbers");
      for (int i=0; i<number.length;i++) {
            number[i] = input.nextInt();
     
        }
    for (int i=0; i<number.length;i++) {
           ++index;
                if (number[i] == numToSearchFor) {
                    index = index-1;
                    System.out.println("Found it at index " + index);
                }
     
     
     
        }
      }
        }
    Works fine, but i was hoping there was a function in the java API that did this.

  6. #5
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: How do you find the the exact index of an element that matches a search in an array?

    Are you expecting the creators of java to anticipate every single function that you can think of and write it for you? Just so when you write your own program it will be a series of method calls to API classes and you never have to write your own code every again!
    Improving the world one idiot at a time!

  7. #6
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default Re: How do you find the the exact index of an element that matches a search in an array?

    Quote Originally Posted by Junky View Post
    Are you expecting the creators of java to anticipate every single function that you can think of and write it for you? Just so when you write your own program it will be a series of method calls to API classes and you never have to write your own code every again!
    That was VERY helpful

  8. #7
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: How do you find the the exact index of an element that matches a search in an array?

    Quote Originally Posted by ojonugwa View Post
    This is what i eventually did
    ...
                if (number[i] == numToSearchFor) {
                   // Then i is the correct index number, just print out i
                   // The variable "index" is unnecessary
    i was hoping there was a function in the java API that did this.
    Perhaps there is, did you look? Check out this page and see what you can find

  9. #8
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default Re: How do you find the the exact index of an element that matches a search in an array?

    import java.util.*;
     
    public class ArrayTest2 {
     
        public static void main(String[] args) {
     
    Scanner input = new Scanner(System.in);
            int[] numbers = {8, 11, 19, 84};
     
     
            int numToSearchFor;
            int i;
     
            for (i = 0; i < numbers.length; i++) {
                System.out.print(numbers[i] + ",");
            }
     
            System.out.println("\nEnter the number to search for: ");
            numToSearchFor = input.nextInt();
     
     
            for (i = 0; i < numbers.length; i++) {
              if (numbers[i] == numToSearchFor) {
                    System.out.println("\nFound "+ numToSearchFor + " at index " + i);
     
            }
        }}}
    This works perfectly, until i add an "else" statement like this
     if (numbers[i] == numToSearchFor) {
                    System.out.println("\nFound "+ numToSearchFor + " at index " + i);break;
     
            } else {
                  System.out.println("Cannot find it");break;
              }
    Then it starts to print "cannot find it"
    Why is that?

  10. #9
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: How do you find the the exact index of an element that matches a search in an array?

    Quote Originally Posted by ojonugwa View Post
    Then it starts to print "cannot find it"
    Why is that?
    That may be because you search one element of the array at a time. When the first index(0) is searched, the if statement is encountered. If there is no match the else executes, the break exits the loop and no other index is considered.
    Follow the loop cycle as it would be executed, you should see how it runs the way described.

  11. The Following User Says Thank You to jps For This Useful Post:

    ojonugwa (August 23rd, 2013)

  12. #10
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default Re: How do you find the the exact index of an element that matches a search in an array?

    Finally got help from my tutor.This is one possible way to do it.
    import java.util.*;
    public class ArrayTest{
    	public static void main (String[]args){
    Scanner input = new Scanner(System.in);
        	int [] number = new int[5];
        	int numberToSearchFor;
        	int i;
        	boolean found=false;
        	for (i=0; i<number.length;i++){
        		number [i] = (int)(Math.random()*20)+1;
        		System.out.println(number[i]); 
        	}
       System.out.println("Enter number to find from available numbers: ");
        	numberToSearchFor = input.nextInt();
        	i=0;
        	while(!found&&i<number.length)
                if (number[i] == numberToSearchFor){
                     System.out.println("Found it at index " + i);
                     found=true;
                }
                else
                	i++;
        	if(!found)
                System.out.println("Cannot find it");
    	}
    }

  13. The Following User Says Thank You to ojonugwa For This Useful Post:

    jps (August 23rd, 2013)

Similar Threads

  1. Linear Search / Index Location of Strings
    By xJavaLover in forum What's Wrong With My Code?
    Replies: 7
    Last Post: February 8th, 2013, 07:11 AM
  2. Binary Search for an array of random ints - Can't find the target value
    By mju516 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 30th, 2012, 11:25 AM
  3. Replies: 1
    Last Post: October 12th, 2011, 04:29 AM
  4. Search for number in array and return index
    By Kevinius in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 24th, 2011, 12:00 AM
  5. how to find an element in an array
    By humdinger in forum Collections and Generics
    Replies: 8
    Last Post: April 9th, 2010, 05:22 PM