繁体   English   中英

从2d阵列中找到最高总数并在JAVA中打印

[英]Find highest total from 2d array and print in JAVA

所以在这里我试图从数组中取一些int并按行添加它们。 然后我将总和存储为rowTotal。 如果rowTotal大于maxRow ....我很累。 有人可以指出明显的吗?

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

您需要从第二个for循环中取出System.out.println 此外,您可以取消第一个for循环。

 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. 你从1开始行,应该是0
  2. 为什么要更改maxRow + = score [0] [col];

这些应该解决你的问题,虽然我不知道它是什么

那么System.out.println(..应该在循环之外。

否则我没有看到这个问题,除了代码可以改进(缩短)的事实。 您得到了什么错误/意外结果?

如果从索引零开始第二个for循环,那么就我所知,不需要第一个for循环。 不知道为什么你在第一个循环中总结maxRow ,除非我完全maxRow了这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM