使用嵌套循环创建交替的拼贴地板

时间:2014-02-17 08:23:41

标签: java

我尝试创建一个程序,根据用户的输入输出备用磁贴设计。 I.E.如果使用输入3,结果将是3x3设计,如下所示:

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

我在为输出获取适量的瓷砖时遇到问题。对于3的输入,第2行有一个额外的" | R |"然后创建第4行。输出结果是:

|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

2 个答案:

答案 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("|");
            }
        }
    }
}

答案 1 :(得分: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