Java圆形计算类代码异常排查与修复:输入半径后结果全为0
Fixing Your Circle Calculation Java Code
Let's walk through the issues in your code and fix them one by one—you're really close, just a few key mistakes throwing everything off!
The Problems in Your Current Code
- Calculation happens before input: You're computing
area,diameter, andcircumferenceright after initializingradiusto 0. At that point, the user hasn't entered any value yet, so all calculations use the default 0 value—hence your 0 results. - Integer type causing precision loss: You're using
intforPi,area,circumference, anddiameter. When you cast3.14toint, it gets truncated to 3, and any decimal results from your calculations will be chopped off too (like 50.24 becomes 50 at best, but since you calculated with 0 first, it's 0). - Variable name typo: In your last
printfstatement, you usedenvironmentinstead ofcircumference—this would actually cause a compile error, not just wrong output.
Fixed Code
package circle; import java.util.Scanner; public class Circle { public static void main(String[] args) { Scanner input = new Scanner(System.in); double radius; // Use double to allow non-integer radii too double diameter; double circumference; double area; final double PI = 3.14; // Use final double for Pi to keep precision // First get the user's input System.out.print("Enter radius value: "); radius = input.nextDouble(); // Use nextDouble to accept decimal radii // Now calculate values AFTER getting the radius diameter = radius * 2; circumference = 2 * PI * radius; area = PI * radius * radius; // Print results with 2 decimal places for readability System.out.printf("Area is %.2f%n", area); System.out.printf("Diameter is %.2f%n", diameter); System.out.printf("Circumference is %.2f%n", circumference); input.close(); // Don't forget to close the scanner! } }
Key Changes Explained
- Swapped input and calculation order: We now get the user's radius first, then do all the math—so we're using the actual input value instead of 0.
- Switched to
doubletypes: This preserves decimal precision for Pi and all calculated values, so you'll get accurate results like 50.24 for radius 4. - Fixed the variable typo: Replaced
environmentwithcircumferenceto match the variable name. - Added
finalto PI: Marking Pi asfinalmakes it clear this is a constant value that shouldn't be changed. - Used
nextDouble(): Allows users to enter non-integer radii (like 4.5) if they want, making the program more flexible. - Closed the scanner: Good practice to clean up resources after use.
If you run this with radius 4, you'll get:
Enter radius value: 4 Area is 50.24 Diameter is 8.00 Circumference is 25.12
内容的提问来源于stack exchange,提问作者M47
相关产品推荐
相关产品推荐

