2014-10-20 57 views
-1
0     
10      
010    
1010      
01010   
101010    
0101010 

这是我的代码,但我总是在不需要的(i%2!= 0)部分打印1。这与数字系统仅仅是一种打印模式无关。为什么这段代码打印下面的零和模式不起作用?

public class Playground { 
public static void main(String[] args) { 
    for (int i = 1; i <= 7; i++) { 
     for (int j = 1; j <= i; j+=2) { 
      if (i % 2 != 0) { 
       System.out.print(0); 
       System.out.print(1); 
      } 
     } 
     for (int j = 1; j <= i; j+=2) { 
      if (i % 2 == 0) { 
       System.out.print(1); 
       System.out.print(0); 
      } 
     } 
     System.out.println(); 

    } 
    } 

} 

回答

0
for (int i = 0; i < 7; i++) { 
    for (int j = i; j >= 0; j--) { 
     System.out.print(j % 2); 
    } 
    System.out.println(); 
} 

或者你也可以做到这一点(由@MitchTalmadge建议):

String output = ""; 
for (int i = 0; i < 7; i++) { 
    output = (i % 2) + output; 
    System.out.println(output); 
} 
+0

您也可以与如果仅仅是System.out.print'(j%2)更换;' – 2014-10-20 00:17:01

+0

是的,在他的情况下这样做会更好。编辑我的帖子。谢谢@thatotherguy – afzalex 2014-10-20 00:22:00

+0

有更好的方法来做到这一点。但是我无法发布,因为问题处于搁置状态。 – 2014-10-20 00:24:07

相关问题