简体   繁体   中英

separating lines of printed text when using printf

Working on a project that requires something to be printed as "printf" but the next line then ends up on the same line as the previous one, how would I go about seperating these?

System.out.print("Cost per course: ");
double costPerCourse1;
costPerCourse1 = keyboard.nextDouble();
System.out.printf("%.2f", costPerCourse1 + /n);

double tuition;
tuition = numberOfClasses1 * costPerCourse1;
System.out.println("Tuition: " + tuition);

You're trying to pass a new line character into the argument String, something that I don't think work. Better is to include "%n" within the format String passed into printf and that will give you an OS independent new line. For example:

System.out.printf("%.2f%n", costPerCourse1);

Or you could simply follow your printf with an empty SOP call.

Edit
I'm wrong. An argument String can have a valid newline char and it works:

public class TestPrintf {
    public static void main(String[] args) {
        String format1 = "Format String 1: %s";
        String arg1 = "\nArgument String 1 that has new line\n";

        System.out.printf(format1, arg1);

        String format2 = "Format String 2 has new line: %n%s%n";
        String arg2 = "Argument String2 without new line";

        System.out.printf(format2, arg2);

    }
}

returns:

Format String 1: 
Argument String 1 that has new line
Format String 2 has new line: 
Argument String21 without new line

Or:

System.out.printf("%s: %.4f%s%s", "Value:", Math.PI, "\n", "next String");

returns:

Value:: 3.1416
next String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM