Question

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);
     }
Was it helpful?

Solution

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);

OTHER TIPS

  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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top