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