java - 小java程序打印不可见的换行符?

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

我正在做一项作业,我已经完成了。这是一个简单的程序,可以打印出字符金字塔。但是,我无法弄清楚为什么当我从未用某些输入指定它时程序会打印换行符,即使它的意思是: /image/jCdI9.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("");
    }
}
}

最佳答案

Small java program prints invisible newline?

在您的程序中,最后一个 System.out.println(""); 会在程序末尾产生额外的一行,即 while(state) 为 < strong>true 在最后,所以要么注释 print 语句,要么在最后设置 state=false

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

关于java - 小java程序打印不可见的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46540971/

相关文章:

java - 线程死锁和同步

java - 我如何取消部署 WildFly 中的所有工件?

java - BASH 脚本将值输入 Java 扫描器

c - 从不兼容的指针类型传递 arg 1 of `strcspn'

java - 从@ElementCollection 中搜索一个对象

Java : double to float type conversion is giving 'infinity' for larger values

Java IO 无法读取文本文件

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

Java Scanner换行识别

C++从文本文件中删除尾随的新行