문제

So here I am trying to take some ints from the array and add them per row. I then store the sum as rowTotal. If rowTotal is greater than maxRow.... I'm tired. Can someone please point out the obvious?

     int maxRow = 0;
     int playNum = 0;

     for(int col = 0;col < score[0].length;col++)
        maxRow += score[0][col];
     for(int row = 1;row < score.length;row++)
     {
         int rowTotal = 0;
         for(int col = 0;col < score[row].length;col++)    
             rowTotal += score[row][col];
         if(rowTotal>maxRow)  
         {
             playNum = row;
             maxRow = rowTotal;
         }
         System.out.println("Player " + (playNum + 1) + " is victorious with a score of " + maxRow);
     }
도움이 되었습니까?

해결책

You need to take the System.out.println out of the second for loop. Also, you can do away with the first for loop.

 int maxRow = 0;
 int playNum = 0;
 for(int row = 0;row < score.length;row++)
 {
     int rowTotal = 0;
     for(int col = 0;col < score[row].length;col++) 
     {
         rowTotal += score[row][col];
     }
     if(rowTotal>maxRow)  
     {
         playNum = row;
         maxRow = rowTotal;
     }

 }
 System.out.println("Player " + (playNum + 1) + " is victorious with a score of " + maxRow);

다른 팁

  1. You're starting row from 1, should be 0
  2. Why do you change maxRow += score[0][col]; ?

These should fix your problem, though I don't know what it is

Well the System.out.println(.. should be outside of the loop.

Otherwise I don't see a problem with this, other than the fact that the code could be improved upon (shortened). What errors/unexpected results are you getting?

If you start the second for loop from index zero then there is no need for the first for loop as far as I can tell. Not sure why you were summing maxRow in the first loop anyway, unless I'm completely missing the point.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top