Piccolo programma java stampa newline invisibile?


Sto facendo un compito e ho finito. Questo è un semplice programma che stampa piramidi di caratteri. Tuttavia, non riesco a capire perché il programma stampa una nuova riga quando non l'ho mai specificata con qualche input, anche se è destinata a: https://i.imgur.com/gPs5oC5.png Perché devo avere una nuova riga in più quando si stampa la piramide capovolta? Dove viene stampata la nuova riga?

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("");
    }
}
}
Author: Senethys, 2017-10-03

2 answers

Piccolo programma java stampa nuova riga invisibile?

Nel tuo programma l'ultimo sistema .fuori.println(""); causa una riga aggiuntiva alla fine del programma, cioè while(state) è true alla fine, quindi o si commenta l'istruzione print o si fa state=false alla fine.

while(state) {    
    ... 
    System.out.println(""); 
}
 1
Author: Zabuza, 2017-10-03 09:24:03

Il ciclo più interno non verrà eseguito se l'input è 0. limit sarà 0, e quindi la condizione del ciclo è false. A partire da questo stamperà en riga vuota, procedendo ad aggiungere 1 anche limite quindi caratteri di stampa.

for (int i = 0; i < length; ++i) {
    for (int counter = 0; counter < limit; counter++) {
        char letter = (char)(counter + 'A');
 0
Author: Senethys, 2017-10-03 09:59:08