小java程序打印隐形换行?

时间:2017-10-03 09:06:44

标签: java java.util.scanner newline user-input system.out

我正在完成任务,我已经完成了。这是一个打印出字符金字塔的简单程序。但是,我无法弄清楚为什么程序在我从未使用某些输入指定它时打印换行符,即使它意味着:https://i.imgur.com/gPs5oC5.png 为什么在颠倒打印金字塔时必须有一个额外的换行符?新线印在哪里?

import java.util.Scanner;

public class Test23 {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in); 

    boolean state = true;

    String messageL = "Length: ";
    String messageD = "Position: ";
    String messageS = "Shutdown!";

    while(state) {
        int limit = 0;
        int degree;

        System.out.print(messageL);
        int length  = input.nextInt();

        while ((length < 1 && length == -1) || length > 26) {

            if (length == -1 ) {
                System.out.println(messageS + "\n");
                state = false;
                break;

            } else {
                System.out.print(messageL);
                length  = input.nextInt();
            }
        }
        if (!state)
            break;
        System.out.print(messageD);
        degree = input.nextInt();

        while((degree > 1) || (degree < 0)) {
            System.out.print(messageD);
            degree = input.nextInt();
        }

        if (degree == 0) 
            //No newline is needed here for some reason.
            length++;

        else if (degree == 1) 
            limit = length;
            //New line here for the pyramids to print symmetrically.
            //System.out.println("");

        for (int i = 0; i < length; ++i) {
            for (int counter = 0; counter < limit; counter++) {
                char letter = (char)(counter + 'A');
                System.out.print(letter);
            }

            if (degree == 0) 
                limit++;

            else if (degree == 1) 
                limit--;

            System.out.println("");
        }

        System.out.println("");
    }
}
}

2 个答案:

答案 0 :(得分:1)

  

小型java程序打印隐形换行符?

在你的程序中,最后一个 System.out.println(&#34;&#34;); 会在程序结束时产生额外的一行,即while(state) <最后是strong> true ,所以要么对print语句发表评论,要么在结束时使用state=false

while(state) {    
    ... 
    System.out.println(""); 
}

答案 1 :(得分:0)

如果输入为0,则最内部循环不会运行。limit将为0,因此循环条件为false。在此之前,它将打印空行,继续添加1 limit然后打印字符。

for (int i = 0; i < length; ++i) {
    for (int counter = 0; counter < limit; counter++) {
        char letter = (char)(counter + 'A');