在Java中,如何为每第5行打印一个空行?

时间:2016-03-16 18:31:11

标签: java loops

这是基本的编程,但我仍然不完全确定如何每隔5行创建一个空白行。请帮忙!谢谢!

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.println("please enter an integer for the length");
    int theLength = input.nextInt();
    System.out.println("Please enter an integer for the height");
    int theHeight = input.nextInt();
    System.out.println("Please enter a character");
    String character1 = input.next();


    //  int character = Integer.toString(character1);

    for (int i = 0; i < theHeight; i++) {     //the outer loop controls the row


        for (int j = 0; j < theLength; j++) {// inner loop control 
            if (j % 6 != 0) { //creates a space for ever 5 character
                System.out.print(character1 + " ");
            } else System.out.print(" ");

        }
        System.out.println();
    }
}

4 个答案:

答案 0 :(得分:1)

如果我理解了您的问题,您可以将elseprint(" ")更改为println;像

if(j%6!=0){ //creates a space for ever 5 character
    System.out.print(character1 + " ");
} else {
    System.out.println();
}

答案 1 :(得分:1)

println("...")方法打印字符串并将光标移动到新行,但print("...")方法只打印字符串,但不会将光标移动到新行。

希望它有所帮助!

答案 2 :(得分:1)

您的循环基于零,因此第0行也可以被5整除:如果符合您的条件,则按如下方式修改for循环:

for (int i = 0; i < theHeight; i++) { // the outer loop controls the row
            for (int j = 0; j < theLength; j++) {// inner loop control
                if (i % 5 != 0) { // creates a space for ever 5 character
                    System.out.print(character1 + " ");
                } else {
                    System.out.print(" ");
                }

            }
            System.out.println();
        }

答案 3 :(得分:0)

  

如何为每第5行打印一个空行?

根据您的代码,在我看来,您希望在每个 n 字符后创建一个空行,而不是在 n 行..

无论您想要在n行或列之后打印空格或换行符,您只需要一个循环。

每5个字符打印一个换行符:

int height = 3, length = 5;
String myChar = "A";

for(int x=0; x<height * length; x++){
    System.out.print(myChar + " ");
    if( (x+1) % length == 0)  // (x+1) so the it won't print newline on first iteration
        System.out.println();
}
  • height * length获取要打印的字符总数
  • (x+1),因为您的x从00 % 0 = 0开始。

<强>输出:

A A A A A 
A A A A A 
A A A A A