我必须编写程序来检查给定第二个数组的所有元素是否为正
如果所有元素都是肯定的,则打印
"阵列的所有元素都是积极的"
这是我的代码:
代码的问题是它多次打印此行!我需要它只打印一次。
public class Demo {
public static void main(String [] args){
int [][] multi = {{2,5,7,-2,-8},{3,7,4,4,5},{2,1,3,8,9},{5,4,8,2,1},{7,8,9,6,-2}};
multiArr(multi);
}
public static void multiArr(int [] [] arr){
for(int i=0; i<arr.length; i++)
for(int j=0; j<arr[0].length; j++)
if(arr[i][j]>0)
System.out.println("All the elements of your array are positive");
}
}
这是控制台中的结果:
All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive All the elements of your array are positive :
答案 0 :(得分:1)
你的for循环应该是:
for(int i=0; i<arr.length; i++)
for(int j=0; j<arr[0].length; j++)
if(arr[i][j]<0) {
System.out.println("Some element in array are negative");
return;//return from method
}
System.out.println("All elements in array are positive");
答案 1 :(得分:0)
问题是你在循环中有你的print语句,所以如果你正在查看的元素是正数,它将在屏幕上显示“正”。我的建议是,添加一个已设置为true的布尔变量,然后如果该元素为负数,则在循环内将其更改为false,然后返回该变量。用它来显示循环外的正字符串。希望这有帮助!