[英]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? 在需要将某些内容打印为“ 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);
You're trying to pass a new line character into the argument String, something that I don't think work. 您正在尝试将新行字符传递到参数 String中,但我认为这行不通。 Better is to include
"%n"
within the format String passed into printf and that will give you an OS independent new line. 更好的做法是在传递给printf的String 格式中包含
"%n"
,这将为您提供独立于操作系统的新行。 For example: 例如:
System.out.printf("%.2f%n", costPerCourse1);
Or you could simply follow your printf with an empty SOP call. 或者,您可以简单地跟随一个空SOP调用您的printf。
Edit 编辑
I'm wrong. 我错了。 An argument String can have a valid newline char and it works:
参数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);
}
}
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.