Array needle in haystack











up vote
1
down vote

favorite












I have an assignment to create an int array that is serched in another method for a user input int value then displays the index of that element in the array. I have that part working just fine and I personaly chose to make the elements in the array random values from 1 - 10.I also need to have the program display a message ("Element not found in array") in the event that the given number isn't in the array. I cannot seem to get this part to work correctly and am hoping I can get some advice here.



import java.util.Scanner;

public class NeedleInHaystack {

public static void main(String args) {
Scanner scan = new Scanner(System.in);

System.out.println("Please provide an Integer for the needle: ");
int needle = scan.nextInt();
int haystack = new int[10];

System.out.println("The array being used is: ");

for (int i = 0; i < 10; i++) {
int j = (int) (Math.random() * 9 + 1);
haystack[i] = j;
System.out.print(haystack[i] + " ");
}

returnIndex(haystack, needle);

}

public static int returnIndex(int haystack, int needle) {
int index = needle;
System.out.println("nThe needle is found at index: ");

for (int i = 0; i < haystack.length; i++) {
if (haystack[i] == index) {
System.out.println(i);
}
}

return index;
}

}


The program is an int needle in a hastack array. What is the best way to make the program end "gracefully" in the event that the input value is not present in the random array?



The assignment was worded as follows:
"Create a Java program with a method that searches an integer array for a specified integer value (see help with starting the method header below). If the array contains the specified integer, the method should return its index in the array. If not, the method should throw an Exception stating "Element not found in array" and end gracefully. Test the method in main with an array that you make and with user input for the "needle"."










share|improve this question
























  • We're interested in one question you're trying to ask, and I can't tell what your question is. We're less interested in reading your whole program or commenting on a few objectives you have. Really you need to narrow it down to just what you're asking.
    – djechlin
    Nov 21 at 22:48










  • the simple question is how to add a contingency to this program - if the input int is not in the array print "Element not found in array"
    – kedrik
    Nov 21 at 22:52

















up vote
1
down vote

favorite












I have an assignment to create an int array that is serched in another method for a user input int value then displays the index of that element in the array. I have that part working just fine and I personaly chose to make the elements in the array random values from 1 - 10.I also need to have the program display a message ("Element not found in array") in the event that the given number isn't in the array. I cannot seem to get this part to work correctly and am hoping I can get some advice here.



import java.util.Scanner;

public class NeedleInHaystack {

public static void main(String args) {
Scanner scan = new Scanner(System.in);

System.out.println("Please provide an Integer for the needle: ");
int needle = scan.nextInt();
int haystack = new int[10];

System.out.println("The array being used is: ");

for (int i = 0; i < 10; i++) {
int j = (int) (Math.random() * 9 + 1);
haystack[i] = j;
System.out.print(haystack[i] + " ");
}

returnIndex(haystack, needle);

}

public static int returnIndex(int haystack, int needle) {
int index = needle;
System.out.println("nThe needle is found at index: ");

for (int i = 0; i < haystack.length; i++) {
if (haystack[i] == index) {
System.out.println(i);
}
}

return index;
}

}


The program is an int needle in a hastack array. What is the best way to make the program end "gracefully" in the event that the input value is not present in the random array?



The assignment was worded as follows:
"Create a Java program with a method that searches an integer array for a specified integer value (see help with starting the method header below). If the array contains the specified integer, the method should return its index in the array. If not, the method should throw an Exception stating "Element not found in array" and end gracefully. Test the method in main with an array that you make and with user input for the "needle"."










share|improve this question
























  • We're interested in one question you're trying to ask, and I can't tell what your question is. We're less interested in reading your whole program or commenting on a few objectives you have. Really you need to narrow it down to just what you're asking.
    – djechlin
    Nov 21 at 22:48










  • the simple question is how to add a contingency to this program - if the input int is not in the array print "Element not found in array"
    – kedrik
    Nov 21 at 22:52















up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have an assignment to create an int array that is serched in another method for a user input int value then displays the index of that element in the array. I have that part working just fine and I personaly chose to make the elements in the array random values from 1 - 10.I also need to have the program display a message ("Element not found in array") in the event that the given number isn't in the array. I cannot seem to get this part to work correctly and am hoping I can get some advice here.



import java.util.Scanner;

public class NeedleInHaystack {

public static void main(String args) {
Scanner scan = new Scanner(System.in);

System.out.println("Please provide an Integer for the needle: ");
int needle = scan.nextInt();
int haystack = new int[10];

System.out.println("The array being used is: ");

for (int i = 0; i < 10; i++) {
int j = (int) (Math.random() * 9 + 1);
haystack[i] = j;
System.out.print(haystack[i] + " ");
}

returnIndex(haystack, needle);

}

public static int returnIndex(int haystack, int needle) {
int index = needle;
System.out.println("nThe needle is found at index: ");

for (int i = 0; i < haystack.length; i++) {
if (haystack[i] == index) {
System.out.println(i);
}
}

return index;
}

}


The program is an int needle in a hastack array. What is the best way to make the program end "gracefully" in the event that the input value is not present in the random array?



The assignment was worded as follows:
"Create a Java program with a method that searches an integer array for a specified integer value (see help with starting the method header below). If the array contains the specified integer, the method should return its index in the array. If not, the method should throw an Exception stating "Element not found in array" and end gracefully. Test the method in main with an array that you make and with user input for the "needle"."










share|improve this question















I have an assignment to create an int array that is serched in another method for a user input int value then displays the index of that element in the array. I have that part working just fine and I personaly chose to make the elements in the array random values from 1 - 10.I also need to have the program display a message ("Element not found in array") in the event that the given number isn't in the array. I cannot seem to get this part to work correctly and am hoping I can get some advice here.



import java.util.Scanner;

public class NeedleInHaystack {

public static void main(String args) {
Scanner scan = new Scanner(System.in);

System.out.println("Please provide an Integer for the needle: ");
int needle = scan.nextInt();
int haystack = new int[10];

System.out.println("The array being used is: ");

for (int i = 0; i < 10; i++) {
int j = (int) (Math.random() * 9 + 1);
haystack[i] = j;
System.out.print(haystack[i] + " ");
}

returnIndex(haystack, needle);

}

public static int returnIndex(int haystack, int needle) {
int index = needle;
System.out.println("nThe needle is found at index: ");

for (int i = 0; i < haystack.length; i++) {
if (haystack[i] == index) {
System.out.println(i);
}
}

return index;
}

}


The program is an int needle in a hastack array. What is the best way to make the program end "gracefully" in the event that the input value is not present in the random array?



The assignment was worded as follows:
"Create a Java program with a method that searches an integer array for a specified integer value (see help with starting the method header below). If the array contains the specified integer, the method should return its index in the array. If not, the method should throw an Exception stating "Element not found in array" and end gracefully. Test the method in main with an array that you make and with user input for the "needle"."







java arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 at 23:26









gfos

342316




342316










asked Nov 21 at 22:44









kedrik

82




82












  • We're interested in one question you're trying to ask, and I can't tell what your question is. We're less interested in reading your whole program or commenting on a few objectives you have. Really you need to narrow it down to just what you're asking.
    – djechlin
    Nov 21 at 22:48










  • the simple question is how to add a contingency to this program - if the input int is not in the array print "Element not found in array"
    – kedrik
    Nov 21 at 22:52




















  • We're interested in one question you're trying to ask, and I can't tell what your question is. We're less interested in reading your whole program or commenting on a few objectives you have. Really you need to narrow it down to just what you're asking.
    – djechlin
    Nov 21 at 22:48










  • the simple question is how to add a contingency to this program - if the input int is not in the array print "Element not found in array"
    – kedrik
    Nov 21 at 22:52


















We're interested in one question you're trying to ask, and I can't tell what your question is. We're less interested in reading your whole program or commenting on a few objectives you have. Really you need to narrow it down to just what you're asking.
– djechlin
Nov 21 at 22:48




We're interested in one question you're trying to ask, and I can't tell what your question is. We're less interested in reading your whole program or commenting on a few objectives you have. Really you need to narrow it down to just what you're asking.
– djechlin
Nov 21 at 22:48












the simple question is how to add a contingency to this program - if the input int is not in the array print "Element not found in array"
– kedrik
Nov 21 at 22:52






the simple question is how to add a contingency to this program - if the input int is not in the array print "Element not found in array"
– kedrik
Nov 21 at 22:52














3 Answers
3






active

oldest

votes

















up vote
0
down vote



accepted










You could add some sort of boolean flag in the method that you set to true if it is found. If not, the flag will remain false. After iterating through the array, you could check whether the flag is false and if so, then you could print some error message.



public static int returnIndex(int haystack, int needle) {

boolean found = false;

int index = needle;
System.out.println("nThe needle is found at index: ");

for (int i = 0; i < haystack.length; i++) {
if (haystack[i] == index) {
System.out.println(i);
found = true;
}
}

if (found) return index;

else {

System.out.println("Not found.");
return null;

}


}

}





share|improve this answer





















  • Ooo this is good too!
    – kedrik
    Nov 21 at 23:01


















up vote
2
down vote













Problem is in for-loop your are checking the needle in array but not return it, and also since you have assigned int index = needle; at the beginning, even though if needle is not in array it will return needle



So in that case assign index=0 in beginning and iterate the array, if found return the index else return the needle



public static int returnIndex(int haystack, int needle) {
int index;
System.out.println("nThe needle is found at index: ");

for (index = 0; index < haystack.length; index++) {
if (haystack[index] == needle) {
System.out.println("value found at index"+index);
return index;
}
}
System.out.println("The value not found in array");

return needle;;
}





share|improve this answer






























    up vote
    0
    down vote













    Since you are supposed to return the index and not the needle value you should just return inside the for-loop once the object is found. Very Similar to what Deadpool did.



    But as you state the method is supposed to throw a exception when the needle isn‘t found you should get rid of the second return statement and just throw a exception.



    public static int returnIndex(int haystack, int needle) {
    System.out.println("nThe needle is found at index: ");

    for (int i = 0; i < haystack.length; i++) {
    if (haystack[i] == needle) {
    System.out.println(i);
    return i;
    }
    }

    throw new NoSuchElementException(„Element not found in array“);
    }





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53421474%2farray-needle-in-haystack%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote



      accepted










      You could add some sort of boolean flag in the method that you set to true if it is found. If not, the flag will remain false. After iterating through the array, you could check whether the flag is false and if so, then you could print some error message.



      public static int returnIndex(int haystack, int needle) {

      boolean found = false;

      int index = needle;
      System.out.println("nThe needle is found at index: ");

      for (int i = 0; i < haystack.length; i++) {
      if (haystack[i] == index) {
      System.out.println(i);
      found = true;
      }
      }

      if (found) return index;

      else {

      System.out.println("Not found.");
      return null;

      }


      }

      }





      share|improve this answer





















      • Ooo this is good too!
        – kedrik
        Nov 21 at 23:01















      up vote
      0
      down vote



      accepted










      You could add some sort of boolean flag in the method that you set to true if it is found. If not, the flag will remain false. After iterating through the array, you could check whether the flag is false and if so, then you could print some error message.



      public static int returnIndex(int haystack, int needle) {

      boolean found = false;

      int index = needle;
      System.out.println("nThe needle is found at index: ");

      for (int i = 0; i < haystack.length; i++) {
      if (haystack[i] == index) {
      System.out.println(i);
      found = true;
      }
      }

      if (found) return index;

      else {

      System.out.println("Not found.");
      return null;

      }


      }

      }





      share|improve this answer





















      • Ooo this is good too!
        – kedrik
        Nov 21 at 23:01













      up vote
      0
      down vote



      accepted







      up vote
      0
      down vote



      accepted






      You could add some sort of boolean flag in the method that you set to true if it is found. If not, the flag will remain false. After iterating through the array, you could check whether the flag is false and if so, then you could print some error message.



      public static int returnIndex(int haystack, int needle) {

      boolean found = false;

      int index = needle;
      System.out.println("nThe needle is found at index: ");

      for (int i = 0; i < haystack.length; i++) {
      if (haystack[i] == index) {
      System.out.println(i);
      found = true;
      }
      }

      if (found) return index;

      else {

      System.out.println("Not found.");
      return null;

      }


      }

      }





      share|improve this answer












      You could add some sort of boolean flag in the method that you set to true if it is found. If not, the flag will remain false. After iterating through the array, you could check whether the flag is false and if so, then you could print some error message.



      public static int returnIndex(int haystack, int needle) {

      boolean found = false;

      int index = needle;
      System.out.println("nThe needle is found at index: ");

      for (int i = 0; i < haystack.length; i++) {
      if (haystack[i] == index) {
      System.out.println(i);
      found = true;
      }
      }

      if (found) return index;

      else {

      System.out.println("Not found.");
      return null;

      }


      }

      }






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 21 at 22:54









      Anish Shanbhag

      1349




      1349












      • Ooo this is good too!
        – kedrik
        Nov 21 at 23:01


















      • Ooo this is good too!
        – kedrik
        Nov 21 at 23:01
















      Ooo this is good too!
      – kedrik
      Nov 21 at 23:01




      Ooo this is good too!
      – kedrik
      Nov 21 at 23:01












      up vote
      2
      down vote













      Problem is in for-loop your are checking the needle in array but not return it, and also since you have assigned int index = needle; at the beginning, even though if needle is not in array it will return needle



      So in that case assign index=0 in beginning and iterate the array, if found return the index else return the needle



      public static int returnIndex(int haystack, int needle) {
      int index;
      System.out.println("nThe needle is found at index: ");

      for (index = 0; index < haystack.length; index++) {
      if (haystack[index] == needle) {
      System.out.println("value found at index"+index);
      return index;
      }
      }
      System.out.println("The value not found in array");

      return needle;;
      }





      share|improve this answer



























        up vote
        2
        down vote













        Problem is in for-loop your are checking the needle in array but not return it, and also since you have assigned int index = needle; at the beginning, even though if needle is not in array it will return needle



        So in that case assign index=0 in beginning and iterate the array, if found return the index else return the needle



        public static int returnIndex(int haystack, int needle) {
        int index;
        System.out.println("nThe needle is found at index: ");

        for (index = 0; index < haystack.length; index++) {
        if (haystack[index] == needle) {
        System.out.println("value found at index"+index);
        return index;
        }
        }
        System.out.println("The value not found in array");

        return needle;;
        }





        share|improve this answer

























          up vote
          2
          down vote










          up vote
          2
          down vote









          Problem is in for-loop your are checking the needle in array but not return it, and also since you have assigned int index = needle; at the beginning, even though if needle is not in array it will return needle



          So in that case assign index=0 in beginning and iterate the array, if found return the index else return the needle



          public static int returnIndex(int haystack, int needle) {
          int index;
          System.out.println("nThe needle is found at index: ");

          for (index = 0; index < haystack.length; index++) {
          if (haystack[index] == needle) {
          System.out.println("value found at index"+index);
          return index;
          }
          }
          System.out.println("The value not found in array");

          return needle;;
          }





          share|improve this answer














          Problem is in for-loop your are checking the needle in array but not return it, and also since you have assigned int index = needle; at the beginning, even though if needle is not in array it will return needle



          So in that case assign index=0 in beginning and iterate the array, if found return the index else return the needle



          public static int returnIndex(int haystack, int needle) {
          int index;
          System.out.println("nThe needle is found at index: ");

          for (index = 0; index < haystack.length; index++) {
          if (haystack[index] == needle) {
          System.out.println("value found at index"+index);
          return index;
          }
          }
          System.out.println("The value not found in array");

          return needle;;
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 at 22:58

























          answered Nov 21 at 22:51









          Deadpool

          3,1112324




          3,1112324






















              up vote
              0
              down vote













              Since you are supposed to return the index and not the needle value you should just return inside the for-loop once the object is found. Very Similar to what Deadpool did.



              But as you state the method is supposed to throw a exception when the needle isn‘t found you should get rid of the second return statement and just throw a exception.



              public static int returnIndex(int haystack, int needle) {
              System.out.println("nThe needle is found at index: ");

              for (int i = 0; i < haystack.length; i++) {
              if (haystack[i] == needle) {
              System.out.println(i);
              return i;
              }
              }

              throw new NoSuchElementException(„Element not found in array“);
              }





              share|improve this answer

























                up vote
                0
                down vote













                Since you are supposed to return the index and not the needle value you should just return inside the for-loop once the object is found. Very Similar to what Deadpool did.



                But as you state the method is supposed to throw a exception when the needle isn‘t found you should get rid of the second return statement and just throw a exception.



                public static int returnIndex(int haystack, int needle) {
                System.out.println("nThe needle is found at index: ");

                for (int i = 0; i < haystack.length; i++) {
                if (haystack[i] == needle) {
                System.out.println(i);
                return i;
                }
                }

                throw new NoSuchElementException(„Element not found in array“);
                }





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Since you are supposed to return the index and not the needle value you should just return inside the for-loop once the object is found. Very Similar to what Deadpool did.



                  But as you state the method is supposed to throw a exception when the needle isn‘t found you should get rid of the second return statement and just throw a exception.



                  public static int returnIndex(int haystack, int needle) {
                  System.out.println("nThe needle is found at index: ");

                  for (int i = 0; i < haystack.length; i++) {
                  if (haystack[i] == needle) {
                  System.out.println(i);
                  return i;
                  }
                  }

                  throw new NoSuchElementException(„Element not found in array“);
                  }





                  share|improve this answer












                  Since you are supposed to return the index and not the needle value you should just return inside the for-loop once the object is found. Very Similar to what Deadpool did.



                  But as you state the method is supposed to throw a exception when the needle isn‘t found you should get rid of the second return statement and just throw a exception.



                  public static int returnIndex(int haystack, int needle) {
                  System.out.println("nThe needle is found at index: ");

                  for (int i = 0; i < haystack.length; i++) {
                  if (haystack[i] == needle) {
                  System.out.println(i);
                  return i;
                  }
                  }

                  throw new NoSuchElementException(„Element not found in array“);
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 at 23:24









                  D. McDermott

                  665




                  665






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53421474%2farray-needle-in-haystack%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Catalogne

                      Violoncelliste

                      Héron pourpré