Question
Beginner Java Programming. Please help me with the first TO-DO in my code. I did the second TO-DO for my getElementIndex method already. (Please write
Beginner Java Programming. Please help me with the first "TO-DO" in my code. I did the second "TO-DO" for my getElementIndex method already. (Please write comments to explain what you're doing for the first TO-DO)
import java.util.Scanner;
public class Lab14
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
double[] numbers = new double[100];
int numElements = 0;
String input;
double element;
int elementIndex;
do
{
System.out.print("Enter a decimal value (q to quit): ");
input = stdIn.next();
if(!input.equalsIgnoreCase("q")) {
numbers[numElements] = Double.parseDouble(input);
numElements++;
}
} while(!input.equalsIgnoreCase("q") && numElements < 99);
/*
* TODO:
* 1. prompt the user for a value to search for
* 2. call the getElementIndex method
* 3. inform the user as to whether or not the
* element was found in the array
*/
System.out.println("Enter a value to search for : ");//1
element = stdIn.nextDouble();
}
public static int getElementIndex(double[] numbers, int numElements, double element)
{
/*
* TODO:
* 1. loop through the elements in the numbers array
* 2. if an element value matches the element parameter,
* then return its index
* 3. if no element value matches the element parameter,
* then return -1
*/
for ( int i =0 ; i < numbers.length; i++)//1
{
if (element == numbers[i])//2
{
return 1;//3
}
return -1;//3
}
}
}
Problem Description
Read through the provided code. It creates an array of doubles that stores decimal values entered by the user until a 'q' is entered.
Read through the TODO comment in the getElementIndex method and write the code to accomplish the tasks it describes.
Read through the TODO comment in the main method and write the code to accomplish the tasks it describes.
Compile and run your program. Test your program with the same input values used in the sample run below.
What output should be :
Enter a decimal value (q to quit): 10.1
Enter a decimal value (q to quit): 10.2
Enter a decimal value (q to quit): 10.3
Enter a decimal value (q to quit): 10.4
Enter a decimal value (q to quit): q
Enter a decimal value to search for: 10.3
10.3 is present in the array at index 2
Enter a decimal value (q to quit): 0.1
Enter a decimal value (q to quit): 0.2
Enter a decimal value (q to quit): 0.3
Enter a decimal value (q to quit): 0.4
Enter a decimal value (q to quit): 0.5
Enter a decimal value (q to quit): q
Enter a decimal value to search for: 0.6
0.6 is not present in the array
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started