Java 使用printf时分隔打印文本的行

Java 使用printf时分隔打印文本的行,java,printf,Java,Printf,在一个需要打印为“printf”的项目中工作,但下一行与前一行在同一行,我如何将它们分开 System.out.print("Cost per course: "); double costPerCourse1; costPerCourse1 = keyboard.nextDouble(); System.out.printf("%.2f", costPerCourse1 + /n); double tuition; tuition = numberOfClasses1 * costPerCo

在一个需要打印为“printf”的项目中工作,但下一行与前一行在同一行,我如何将它们分开

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);

您试图将一个新行字符传递到参数字符串中,我认为这是行不通的。更好的方法是在传递到printf的格式字符串中包含
“%n”
,这将为您提供一个独立于操作系统的新行。例如:

System.out.printf("%.2f%n", costPerCourse1);
或者,您可以简单地按照printf执行一个空的SOP调用

编辑
我错了。参数字符串可以具有有效的换行符,并且可以工作:

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);

    }
}
返回:

Format String 1: 
Argument String 1 that has new line
Format String 2 has new line: 
Argument String21 without new line
Value:: 3.1416
next String
或:

返回:

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

你希望输出什么?忍者D!-嗯,老实说,它适用于
%s
%c
-即
系统.out.printf(“%.2f%c”,costPerCourse1,“\n”)-我并不是说这是一个好的解决方案(它不是,因为
%n
或者格式上的普通
\n
显然更好)-但它会起作用。@huntervike:我错了,参数字符串可以有一个有效的换行字符。请参见编辑答案。@vaxquis:谢谢您的评论。我想我是在你发表评论的同时发布我的编辑。@HovercraftFullOfEels