JAVA ::::Need help when I enter my numbers into the complier I get largest index
ID: 673593 • Letter: J
Question
JAVA ::::Need help when I enter my numbers into the complier I get largest index is 41
Please send screenshots after its ran in complier
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
This is my answer
import java.util.Scanner;
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 largest is " +
indexOfLargestElement(numbers)+1);
}
public static int indexOfLargestElement(double[] list) {
double largest = list[0];
int largestIndex = 0;
for (int i = 1; i < list.length; i++)
if (largest > list[i]) {
largest = list[i];
largestIndex = i;
}
return largestIndex;
}
}
Explanation / Answer
public static void main(String[] args) { double numbers []= {1.9,2.5,3.7,2,1.5,6,3,4,5,2}; int index= indexOfLargestElement(numbers); System.out.println("The index of the largest number is: "+index); } public static int indexOfLargestElement(double[] array){ int index=0; double largest=0; for (int i = 0; i largest){ largest= array[i]; index=i; } } return index; }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.