문제

My System.out Java lines are not executing properly thus causing them to print half of each line all on one line. I'm not sure what's wrong here. According to my notes, they appear to look okay. Any thoughts?

Code:

System.out.printf("The circumference of a circle with radius ", radius,  " is: ", circumference, ".\n");
System.out.printf("The area of a circle with radius ", radius, " is: ", areacircle, ".\n");
System.out.printf("The area of a sphere with radius ", radius, " is: ", areasphere, ".\n");
System.out.printf("The volume of a sphere with radius ", radius, " is: ", volumesphere, ".\n");

Output:

Enter radius: 2.5 The circumference of a circle with radius The area of a circle with radius The area of a sphere with radius The volume of a sphere with radius

도움이 되었습니까?

해결책

You're not using printf right. This:

System.out.printf("The circumference of a circle with radius ", radius,  " is: ", circumference, ".\n");

should be:

System.out.printf("The circumference of a circle with radius %.2f is: %.2f%n", 
     radius, circumference);

Where the %f is a placeholder for your floating point (presumably double here) values. The whole idea behind printf is to avoid the ugly String concatenation that you're doing in your code. Note that you should use %n for end of line in printf and similar code, not \n.

For more details you will want to look at the api for the java.util.Formatter class.

다른 팁

To properly use printf, provide the format all in the first argument, and supply values with all other arguments. Use placeholders for values. Example for the first line:

System.out.printf("The circumference of a circle with radius %f is %f.\n",
    radius, circumference);

Also see the formatting summary.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top