Database System Concepts
Database System Concepts
7th Edition
ISBN: 9780078022159
Author: Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher: McGraw-Hill Education
Bartleby Related Questions Icon

Related questions

Question

In Java please.

Add comments too!

thank you!

Transcribed Image Text: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". public static int returnIndex(int[] haystack, int needle) {
Expert Solution
Check Mark
Step 1

code-

import java.util.Scanner;
public class Main
{ public static int returnindex(int[] haystack , int needle) {

if (haystack == null) {
return -1;
}

int len = haystack.length;
int i = 0;
while (i < len) {
if (haystack[i] == needle) {
return i;
}
else {
i = i + 1;
}
}
return -1;

}

public static void main(String[] args) {
int[] haystack = { 1,2,3,4,5,6 };
Scanner sc = new Scanner(System.in);
int needle = sc.nextInt();
if (returnindex(haystack,needle)>=0){
System.out.println(returnindex(haystack,needle));}
else{
throw new ArithmeticException("Element not found in array");
}
}
}

Knowledge Booster
Background pattern image
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
    SEE MORE QUESTIONS
    Recommended textbooks for you
    Text book image
    Database System Concepts
    Computer Science
    ISBN:9780078022159
    Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
    Publisher:McGraw-Hill Education
    Text book image
    Starting Out with Python (4th Edition)
    Computer Science
    ISBN:9780134444321
    Author:Tony Gaddis
    Publisher:PEARSON
    Text book image
    Digital Fundamentals (11th Edition)
    Computer Science
    ISBN:9780132737968
    Author:Thomas L. Floyd
    Publisher:PEARSON
    Text book image
    C How to Program (8th Edition)
    Computer Science
    ISBN:9780133976892
    Author:Paul J. Deitel, Harvey Deitel
    Publisher:PEARSON
    Text book image
    Database Systems: Design, Implementation, & Manag...
    Computer Science
    ISBN:9781337627900
    Author:Carlos Coronel, Steven Morris
    Publisher:Cengage Learning
    Text book image
    Programmable Logic Controllers
    Computer Science
    ISBN:9780073373843
    Author:Frank D. Petruzella
    Publisher:McGraw-Hill Education