Write a Java program named FindLargest with the following requirements: 1. Write
ID: 673193 • Letter: W
Question
Write a Java program named FindLargest with the following requirements:
1. Write a method that returns the index of the largest element in an array of integers. If the number of such elements is greater than 1, return the index of the largest element. Use the following header:
public static int indexOfLargestElement(double[] array)
2. Write a main method that prompts the user to enter ten numbers, invokes this method to return the index of the largest element, and displays the index. Take note of the sample run of the program below:
Sample:
Enter ten numbers: 1.9 2.5 3.7 2 1.5 6 3 4 5 2
The index of the largest element is 5
HINT: When searching array for largest element, use a temporary variable to hold ‘max’ candidates, replacing that candidate with a new max until the end of your search.
This is what I got and I know I missed something somewhere HELP!!!
public class LargestElement {
public static void main(String[] args) {
double[] numbers = new double[10];
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter ten numbers: ");
for (int i = 0; i < numbers.length; i++)
numbers[i] = input.nextDouble();
System.out.println("The index of the min is " +
indexOfLargestElement(numbers));
}
public static int indexOfLargestElement(double[] list) {
double min = list[0];
int minIndex = 0;
for (int i = 1; i < list.length; i++)
if (min > list[i]) {
min = list[i];
minIndex = i;
}
return minIndex;
}
}
Explanation / Answer
package mani;
public class LargestElement {
public static void main(String[] args) {
double[] numbers = new double[10];
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter ten numbers: ");
for (int i = 0; i < numbers.length; i++)
numbers[i] = input.nextDouble();
System.out.println("The index of the min is " +
(indexOfLargestElement(numbers)+1));//added one here
}
public static int indexOfLargestElement(double[] list) {
double min = list[0];
int minIndex = 0;
for (int i = 1; i < list.length; i++)
if (min > list[i]) {
min = list[i];
minIndex = i;
}
return minIndex;
}
}
Instead of starting from 0 your instructor have asked the list to index from 1 to 10 instead of 0 to 9 so just add one to the return value
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.