问题
I am trying to just get the sum of row 2. My code compiles but doesn't print anything. Some guidance? Also, building off of the first question, how would I access the largest element in column 3?
import java.util.*;
public class TestCode {
public static void main(String[] args) {
int array[][] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};
int sum = 0;
//print(array);
}
public static void print(int list[][]) {
for(int row = 0; row < list.length;row++) {
int[] sum = new int [3];
for(int column = 0; column < list[row].length; column++) {
sum[1] = list.length;
}
System.out.println(sum);
}
}
}
回答1:
try
public class Test {
public static void main(String[] args) {
int array[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
FindLargestInColumn(array, 2);
FindSumforRow(array,2);
}
public static void FindLargestInColumn(int list[][], int index) {
int largest = -1;
for (int[] row : list) {
if (row[index] > largest)
largest = row[index];
}
System.out.println("The Largest value in column " + (index )+ " is " + largest);
}
public static void FindSumforRow(int list[][], int rowIndex) {
int sum = 0;
int[] row = list[rowIndex];
for (int value : row) {
sum = sum + value;
}
System.out.println("The Sum of value in row " + (rowIndex)+ " is " + sum);
}
}
回答2:
try this code
public static void print(int list[][]) {
int sum = 0;
int arrSum[] = new int[3];
for (int column = 0; column < list[1].length; column++) {
arrSum[column] = list[1][column];
sum += list[1][column];
}
System.out.println("array " + Arrays.toString(arrSum) + " sum =" +sum);
}
回答3:
This is what you are looking for, Pls correct me if i misunderstood your doubt.
public static void main(String[] args) throws UnknownHostException {
int array[][] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};
int sum = 0;
print(array,2); // 2 here is rowNumber, can be replaced with other no
}
public static void print(int list[][], int rowNumber) {
for(int row = 0; row < list.length;row++) {
int sum =0;
if(row == (rowNumber-1)){
for(int column = 0; column < list[row].length; column++) {
sum += list[row][column];
}
System.out.println(sum);
}
}
}
来源:https://stackoverflow.com/questions/19486521/java-array-sum-of-specific-row