Hello everyone, I'm new to Java. I found this site and the members to have a lot of knowledge and was hoping I can get some assistance.
I have written this 2D array code to find the lowest value in each row and return the values. "getLowestInRow" is the method I'm using. This method should return the total of the lowest value in the specified row of array. I can get it to return only if I have this in the loop: "System.out.println("The lowest of row " + row + " is " + low);"
This is the result that I get:
The lowest of row 0 is 1
The lowest of row 1 is 4
The lowest of row 2 is 7
The lowest of row 3 is 10
4 x 3 array
The lowest of row 0 is 1
The lowest of row 1 is 4
The lowest of row 2 is 7
The lowest of row 3 is 10
How can I have the method return the total of the lowest value in the specified row of array without a print statement in the loop. If I remove the statement, the method does not return anything, but with it in, it prints while going through loop and when it's return. Thanks in advance.
public class IssueWithDoublePrint
{
public static void main (String [] args)
{
// Declare a 2D array with 4 rows and 3 columns.
int [] [] array = {{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}};
// Initialize
int total = 0;
int row = 0;
int col = 0;
int rowLowestOfArray = getLowestInRow(array);
// Display the outputs.
System.out.println("");
System.out.println(array.length + " x " + array[col].length + " array");
System.out.println("");
getLowestInRow(array);
}
//Finding the lowest value of the elements in the array in a row and returning the value
public static int getLowestInRow (int [] [] array)
{
int low = array [0] [0];
for (int row = 0; row < array.length; row++)
{
// Setting low to 0
low = 0;
for (int col = 0; col < array[row].length; col++)
if (array[row][col] > low)
{
low = array[row][col];
}
for (int col = 0; col < array[row].length; col++)
{
if (array[row][col] < low)
low = array[row][col];
}
System.out.println("The lowest of row " + row + " is " + low);
}
return low;
}
}