我想根据条件打印2Darray的总和。如果2Darray条件-1整数中的一行加上该行的总和并排除-1整数。否则,如果2Darray中的某行没有conation -1整数,则跳过该行并且不加总和
public class Mainclass {
public static void main(String[] args) {
int[][] places = {
{ 2, 3, -1 },
{ -1, 4, 5 },
{ 2, 3, 4 } };
int ch = -1, col;
int sum = 0;
for (int row = 0; row < places.length; row++) {
for (col = 0; col < places[row].length; col++) {
if (places[row][col] == ch) // skip the -1 integer in 2D array
{
}
if (ch != places[row])
// here i want to diselected the row that do not conatin -1
// integer
// skip row that does not contain -1
{
}
sum += places[row][col];
// print the sum of row that contain -1 and also exclude -1
// integer in sum
}
}
System.out.println(sum);
// and the sum should be 2+3+4+5=14
}
}
答案 0 :(得分:1)
如果为-1,则只能出现一次,它将起作用:
int [][] places = {
{2,3,-1},
{-1,4,5},
{2,3,4}
};
int sum=0;
for(int row=0;row<places.length;row++)
{
if(Arrays.stream(places[row]).filter(x->x==-1).findAny().isPresent()){
sum+=Arrays.stream(places[row]).sum()+1;
}
}
输出:
14
答案 1 :(得分:0)
您可以为每一行计算一个临时总和,如果没有-1
,您将只添加到最终总和中。
看到此示例并附带一些评论:
public static void main(final String args[]) throws IOException, ParseException {
int[][] places = {
{ 2, 3, -1 },
{ -1, 4, 5 },
{ 2, 3, 4 }
};
int ch = -1, col;
int sum = 0;
for (int[] place : places) {
int tempSum = 0; // sum of the current row only
boolean containsMinusOne = false;
for (col = 0; col < place.length; col++) {
if (place[col] == ch) // skip the -1 integer in 2D array
{
containsMinusOne = true;
continue; // skip the rest of this iteration, -1 won't be added to the temp sum below.
}
tempSum += place[col];
}
// if there was a -1, add the sum of this row
if (containsMinusOne) {
sum += tempSum;
}
}
System.out.println(sum);
}
答案 2 :(得分:0)
仅使用简单的for...each
怎么办?在我看来,它看起来非常简单清晰:
public static long sum(int[][] places) {
long res = 0;
for (int[] row : places) {
int sum = 0;
boolean apply = false;
for (int col : row) {
if (col != -1)
sum += col;
else
apply = true;
}
res += apply ? sum : 0;
}
return res;
}
示例:
int[][] places = { { 2, 3, -1 }, { -1, 4, 5 }, { 2, 3, 4 } };
System.out.println(sum(places)); // 14
答案 3 :(得分:0)
解决方案可以是直接的,找到行总和并保留一个布尔变量,该变量检查行是否包含-1。
如果布尔变量的值为true,则将行总和添加到总计中,否则将其跳过。
int [][] places = {
{2,3,-1},
{-1,4,5},
{2,3,-1}
};
int ch=-1,col;
int sum=0;
for(int row=0;row<places.length;row++)
{
boolean rowCheck = false;
int rowSum=0;
for( col=0;col<places[row].length;col++)
{
rowSum+=places[row][col];
// print the sum of row that contain -1 and also exclude -1 integer in sum
if(places[row][col]==ch) // skip the -1 integer in 2D array
{
rowCheck=true;
rowSum+=1;
}
}
if(rowCheck)
sum+=rowSum;
}
System.out.println(sum);
答案 4 :(得分:0)
这是一个非常直观的Stream api解决方案。
Arrays
.stream(places)
.filter(row -> Arrays.stream(row).anyMatch(x -> x == ch))
.mapToInt(row -> Arrays.stream(row).filter(x -> x != ch).sum())
.sum()