newI
또는 newJ
의 유형을 정의하지 마십시오. 신고 유형을 원하는 유형 (예 : int
) 앞에 붙여서 수정할 수 있습니다. 또한 if 문 앞에 두 개의 "`"가 있고 else 문 앞에 닫는 괄호 "}"가 없습니다. 그러나 그것들은 단지 구문상의 오류입니다. 이러한 오류를 수정하면 메서드가 원하는 결과를 반환하지 않음을 알게됩니다.
코드, 특히 for 루프를 살펴보십시오. 외부 루프가 만들어 반복
for(int i=0; i< maxRows.length; i++) {
newI += i;
for(int j=0; j< maxRows.length; j++) {
newJ += j;
// other stuff
}
}
이의이
maxRows.length
는 외부 루프는 2 0에서 실행하는 것입니다 의미 (3)에 해당한다고 가정 해 봅시다, 그래서
newI
은 내부 루프 반복을, 각각의 사이에 3 번 3. 동일합니다. 따라서
newJ
은 9와 동일하게 끝날 것입니다. 배열 요소를 합산하는 올바른 방법이 아닙니다. 더 좋은 방법은 바깥 쪽 루프의 배열을 반복하고 내부 루프의 요소를 합친 다음 바깥 쪽 루프를 완성하는 비교를하는 것입니다. 좋아요 :
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
다음은 달성하려는 목표의 예입니다.
public class RowSums {
public static void main(String[] args) {
int[][] test = { {1, 5, 7, 0, 9} , {2, 4, 5, 6, 7} , {9, 2, 0, 12, 8, 3} };
System.out.println(printRows(test));
System.out.println("The row with the largest sum is row "
+ findMaxRow(test));
}
public static int findMaxRow(int[][] maxRows){
int largestRow = 0;
int largestSum = 0;
int sum;
// iterate over each array
for(int i=0; i< maxRows.length; i++) {
sum = 0; // set and reset sum to zero
// iterate over each element
for(int j=0; j< maxRows[i].length; j++) {
sum += maxRows[i][j];
}
// if sum is > the previous largest sum then set largest
// sum to this new sum and record which row
if(sum > largestSum) {
largestRow = i;
largestSum = sum;
}
}
return largestRow;
}
public static String printRows(int[][] rows) {
StringBuilder s = new StringBuilder("Rows and their sums:\n");
int sum;
for(int x = 0; x < rows.length; x++) {
s.append("Row [" + x + "] = [ ");
sum = 0;
for(int y = 0; y < rows[x].length; y++) {
s.append(rows[x][y] + " ");
sum += rows[x][y];
}
s.append("]\n");
s.append("Row [" + x + "]'s sum is " + sum + "\n");
}
return s.toString();
}
}
출력 :
Rows and their sums:
Row [0] = [ 1 5 7 0 9 ]
Row [0]'s sum is 22
Row [1] = [ 2 4 5 6 7 ]
Row [1]'s sum is 24
Row [2] = [ 9 2 0 12 8 3 ]
Row [2]'s sum is 34
The row with the largest sum is row 2
당신은 두 개의 "'"당신의'if' 문 및 누락 닫는 괄호 "}"이전하기 전에'else' 문이있다. 또한, newI는'i'' maxRows.length' 번을 더하고'newJ'는'j''의 값을 더하기 때문에'newI'는'newJ'보다 클 수 없습니다. maxRows.length'^2 번. –
@ aokk3 내 대답을 확인하십시오. –