[英]separating lines of printed text when using 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);
您正在尝试将新行字符传递到参数 String中,但我认为这行不通。 更好的做法是在传递给printf的String 格式中包含"%n"
,这将为您提供独立于操作系统的新行。 例如:
System.out.printf("%.2f%n", costPerCourse1);
或者,您可以简单地跟随一个空SOP调用您的printf。
编辑
我错了。 参数String可以具有有效的换行符char,并且可以工作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.