2015-02-23 154 views
-2

我必须写程序来检查,如果给定2个数组中的所有元素都是正
如果一切积极的因素是打印
“所有的你的数组中的元素都是正”打印多行有两个for循环

这里是我的代码:
多次打印此行代码的问题!我只需要它打印一次。

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 
: 
+2

这是一个家庭作业吗?它看起来像一个。无论哪种情况,请查看http://meta.programmers.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems – such 2015-02-23 15:41:48

回答

0

的问题是你有你的打印语句的循环中,所以如果您正在查看的元素是正面的,它将在屏幕上显示“正面”。我的建议是,添加一个已经设置为true的布尔变量,然后如果该元素为负值,请在您的循环内将其更改为false,然后返回该变量。用它在循环外显示你的正字符串。希望这可以帮助!

+0

是的,它工作与boo-lean变量,非常感谢! :) – Nida 2015-02-23 15:54:00

1

您的循环应该是这样的:

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"); 
+0

谢谢,非常感谢:) – Nida 2015-02-23 15:43:04