[英]Java: 2D array minimum and maximum values
I am working on this program to find minium and maximum values of the variable milesTracker and have been successful for a few tests but it breaks testing it with values {{-5}, {-93}, {-259}}.我正在开发这个程序来查找变量milesTracker 的最小值和最大值,并且已经成功进行了几次测试,但是它用值{{-5}、{-93}、{-259}} 进行了测试。
Note: I cannot edit anything outside of the commented area, however, I can add more lines anywhere within the commented area.注意:我无法编辑评论区域之外的任何内容,但是,我可以在评论区域内的任何位置添加更多行。
I'd appreciate the help.我很感激你的帮助。
My code:我的代码:
import java.util.Scanner;
public class ArraysKeyValue {
public static void main (String [] args) {
final int NUM_ROWS = 2;
final int NUM_COLS = 2;
int [][] milesTracker = new int[NUM_ROWS][NUM_COLS];
int i = 0;
int j = 0;
int maxMiles = 0; // Assign with first element in milesTracker before loop
int minMiles = 0; // Assign with first element in milesTracker before loop
milesTracker[0][0] = -10;
milesTracker[0][1] = 20;
milesTracker[1][0] = 30;
milesTracker[1][1] = 40;
// Start of area to be modified
for(i=0;i<NUM_ROWS;++i){
for(j=0;j<NUM_COLS;++j){
if (milesTracker[i][j]<minMiles){
minMiles = milesTracker[i][j];
}
else if (milesTracker[i][j] > maxMiles){
maxMiles = milesTracker[i][j];
}
}
}
// End of area to be modified
System.out.println("Min miles: " + minMiles);
System.out.println("Max miles: " + maxMiles);
}
}
Errors:错误:
// Start of area to be modified
maxMiles = milesTracker[0][0];
minMiles = milesTracker[0][0];
for(i=0; i < NUM_ROWS; i++){
for(j=0; j < NUM_COLS; j++){
if (milesTracker[i][j] < minMiles){
minMiles = milesTracker[i][j];
}
else if (milesTracker[i][j] > maxMiles){
maxMiles = milesTracker[i][j];
}
}
}
You initialize,你初始化,
int maxMiles = 0;
Yet you only update maxMiles
,然而你只更新maxMiles
,
if(milesTracker[i][j] > maxMiles)
while iterating through your array with {{-5},{-93},{-253}}
, none of those values are greater than maxMiles == 0
.在使用{{-5},{-93},{-253}}
迭代数组时,这些值都不大于maxMiles == 0
。 Thus maxMiles
is never updated.因此maxMiles
永远不会更新。
Try declaring it arbitrarily within the set尝试在集合中任意声明它
int maxMiles = milesTracker[0][0];
Then maxMiles
cannot be out of the set.那么maxMiles
不能在集合之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.