Pregunta

I can't figure out why my code is causing the PrintStream to go to a new line:

// displays the total time of the leak in months from the calculateLeakTime() method. 
    String leakTime = LeakCalculator.calculateLeakTime(); 
    System.out.println("The total time of the leak is " + leakTime + " months.");

The output looks like this:

"The total time of the leak is 12
months."

I can't figure out why months is being printed on a new line. I even tried this:

// displays the total time of the leak in months from the calculateLeakTime() method. 
    String leakTime = LeakCalculator.calculateLeakTime(); 
    System.out.print("The total time of the leak is " + leakTime);
    System.out.println(" months.");

And I got the same output. Can someone explain why it's moving "months" to a new line?

Thanks,

Kevin

EDIT: Here's the calculatLeakTime() method:

static String calculateLeakTime() throws ParseException{

    long leakEndMili = getLeakEnd(); 
    long leakBeginMili = getLeakBegin(); 

    long timeDays = ((leakEndMili - leakBeginMili) / (1000 * 60 * 60 * 24));

    double timeMonths = (double) (timeDays * 0.0328549); 

    System.out.println(timeMonths);

    String monthsRounded = String.format("%.0f%n", timeMonths); 

    return monthsRounded; 
    }
¿Fue útil?

Solución

Remove "%n" from the following line:

String monthsRounded = String.format("%.0f%n", timeMonths);

Otros consejos

It's doing this because your LeakCalculator.calculateLeakTime() method adds a line feed, "\n" to the end of the String that it returns. To tell for sure, print out the individual chars that make up the String returned.

To solve this, fix your LeakCalculator.calculateLeakTime() method so that it doesn't add a line-feed to its returned String. Perhaps it should return a number and not a String.


Edit
You state:

I suspect this is the issue format("%.0f%n", timeMonths)

Well yes, %n is a new-line character.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top