Joseph Joseph - 13 days ago 9
Java Question

Locate the largest element in a multidimensional arrays

I have to write a program using a method that returns the location of the largest element in a two dimensional array.

example

Enter the number of rows and columns of the array:

3 4

Enter the array:

23.5 35 2 10

4.5 3 45 3.5

35 44 5.5 9.6

the location of the largest element is at (1, 2)

I have finished my code but it isn't working. How can I fix it? All I got are the following errors:

symbol : variable maxvalue

location: class int[]

if (a[i][j] > largest.maxvalue)
^


homework1a.java:51: row is already defined in locateLargest(double[][])

double row = i;
^


homework1a.java:52: column is already defined in locateLargest(double[][])

double column = j;
^


homework1a.java:53: maxValue is already defined in locateLargest(double[][])

double maxValue = a[i][j];
^


homework1a.java:88: i is already defined in main(java.lang.String[])

for (int i = 0; i < 2; i++)
^


5 errors

My code

import java.util.Scanner;
public class hwm1 {

public static int[] locateLargest(double[][] a)
{

int[] largest = new int[2];

double row = 0;
double column = 0;
double maxValue = a[0][0];

for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a.length; j++)
{
if (a[i][j] > largest.maxvalue)
{
double row = i;
double column = j;
double maxValue = a[i][j];
}
}
}

return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);

//User input rows and columns
System.out.println("Enter the number of rows and columns in the array: ");

int numberOfRows = input.nextInt();
int numberOfColumns = input.nextInt();


//User input data in array
System.out.println("Enter numbers into array: ");
//Create array
double[][] a = new double[numberOfRows][numberOfColumns];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
a[i][j] = input.nextDouble();
}
int[] largest = locateLargest(a);
System.out.println("The location of the largest element is at "+ "("+largest[0] +", " + largest[1] + ")");
for (int i = 0; i < 2; i++)
{
System.out.print(largest[i]);
}
}
}


}

Answer

You are declaring the variables row, column and maxValue twice.

enter image description here

Also, in the line:

 if (a[i][j] > largest.maxvalue)

There is no such thing as maxvalue in your code, and neither is it a member of largest

In this part of your code:

enter image description here

Since i is already declared in the outer for-loop, you don't need to declare it again. Just use:

...
 for(i = 0; i < 2; i++){
   ...
}
Comments