2014-02-17 44 views
1

我正在尝试创建一个程序,用于从用户的输入中输出替代瓷砖设计。 I.E.如果3结果运用投入将是一个3x3的设计,看起来像:使用嵌套循环创建交替式瓷砖地板

|R|B|R| 
|B|R|B| 
|R|B|R| 

我遇到了越来越瓷砖适量的输出问题。对于3的输入,第2行有一个额外的“| R |”随后创建第四行。输出出来到:

|R|B|R| 
|B|R|B|R| 
|R|B|R| 
|B 

我下面附上我的代码。我知道它有什么关系:

if (r%2 == 0){ 
System.out.println("|"); 
System.out.print("|B"); 

有什么想法?

import java.util.*; 

public class tileFloor { 

    public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Scanner input = new Scanner (System.in); 
    System.out.println("Enter x:"); 
     int x; 
      x = input.nextInt(); 

    if (x < 10) 
    { int c = 0; 
     int r = 0; 

     while (r < x){ 
      while (c < x){ 
       if (c %2 == 0) 
       System.out.print("|R"); 
       else if (c%2 != 0) 
       System.out.print("|B"); 

      c++; 

      }//end 'while (c<x)' loop 

     if (r%2 == 0){ 
      System.out.println("|"); 
      System.out.print("|B"); 
     } 
     else if (r%2 != 0) 
      System.out.println("|"); 

     c = 0; 
     r++; 

     }//end 'while (r<x)' loop 

    }//end if statement 

    input.close(); 

}//end main 

}//end class 
+0

为什么不使用for循环而不是一段时间?既然你知道它应该迭代的次数? – Marcus

+0

这听起来像一个好主意,但我对它们并不舒服 – Cullen

+0

你应该对它们感到满意。尽管循环很危险,因为一个简单的错误可能意味着它们永远不会退出Far循环不太可能发生循环。 – DFreeman

回答

0

试试这个

import java.util.*; 

class tileFloor { 

    public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Scanner input = new Scanner (System.in); 
    System.out.println("Enter x:"); 
     int x; 
      x = input.nextInt(); 
    int count = 0; 
    if (x < 10) 
    { int c = 0; 
     int r = 0; 

     while (r < x){ 
     if(r%2 == 0) 
     { 
      count = 0; 
     } 
     else 
     { 
      count = 1; 
     } 
      while (c < x){ 


       if (count %2 == 0) 
       { 
        System.out.print("|R"); 
       } 
       else 
       { 
        System.out.print("|B"); 
       } 

      count++; 
      c++; 

      }//end 'while (c<x)' loop 


      System.out.println("|"); 

     c = 0; 
     r++; 

     }//end 'while (r<x)' loop 

    }//end if statement 

    input.close(); 

}//end main 

}//end class 
+0

这工作正常与奇数输入,但不交替甚至输入 – Cullen

+0

是的,我正在对它 –

+0

我修改了它... :) –

1

这个怎么样的解决方案?它明确地更清楚它是什么:

public static void main(String[] args) { 
    try (Scanner input = new Scanner(System.in)) { 
     System.out.print("Enter x: "); 
     int x = input.nextInt(); 

     if (x < 10) { 
      int r = x; 
      int c; 

      while (r-- > 0) { 
       c = x; 

       while (c-- > 0) { 
        System.out.print("|" + ((c + r & 1) == 0 ? "R" : "B")); 
       } 

       System.out.println("|"); 
      } 
     } 
    } 
} 
+0

对于Odd输入它可以正常工作,但即使它不会... –

+0

好吧,OP没有真正提到他期待的结果......但现在我猜测它就像是一个象棋领域。 ..我纠正了我的答案! – bobbel

+0

绝对清晰,但如上所述,我有for循环的麻烦。不过谢谢你的回应! – Cullen