使用printf时分隔打印文本行

时间:2015-09-20 15:18:52

标签: java printf

处理一个需要打印为“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);

1 个答案:

答案 0 :(得分:2)

您正在尝试将新行字符传递到参数字符串中,这是我认为无法正常工作的内容。更好的是将"%n"包含在传递给printf的格式字符串中,这将为您提供独立于操作系统的新行。例如:

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

或者你可以通过空SOP电话跟随你的printf。

修改
我错了。参数String可以有一个有效的换行符,它可以工作:

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

或者:

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

返回:

Value:: 3.1416
next String