我不知道如何初始化半径,以便用户可以在提示时输入半径,而不是将设置值设置为半径。我想我其他所有东西都在这里,但我不能为我的生活弄清楚这一点。 我在这里错过了什么?请帮忙
import java.util.Scanner;
import java.text.DecimalFormat;
public class CircleCalc
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
double radius;
double area = Math.PI * radius * radius;
double circum = 2 * radius * Math.PI;
DecimalFormat formatter = new DecimalFormat("#.0000");
int choice;
System.out.println("CIRCLE CALCULATOR MENU");
System.out.println("1) Calculate the Area of a Circle");
System.out.println("2) Calculate the CIrcumference of a Circle");
System.out.println("3) Quit the Program");
System.out.println("Make a selection by choosing a number:");
choice = keyboard.nextInt();
if (choice == 1)
{
System.out.println("What is the radius of the Circle?");
radius = keyboard.nextInt();
System.out.println(" The Area of the Circle with radius " + radius + " is " + area);
}
else if (choice == 2)
{
System.out.println("What is the radius of the Circle?");
radius = keyboard.nextInt();
System.out.println("The Circumference of the Circle with radius " + radius+ " is " + formatter.format(circum));
}
else if (choice == 3)
{
System.out.println("You have chosen to quit the program.");
}
else if (choice >3)
{
System.out.println("You have made an invalid selection.");
}
}
}
答案 0 :(得分:0)
这是你的问题。
Scanner keyboard = new Scanner(System.in);
double radius;
double area = Math.PI * radius * radius;
double circum = 2 * radius * Math.PI;
您尚未初始化半径值,但同时在计算面积和周长时使用它。首先从用户那里获得输入。先做radius = keyboard.nextInt();
。
您可以在获得用户的半径值后进行计算。
希望有所帮助
答案 1 :(得分:0)
看起来你想定义函数来计算任何半径的周长和面积(因为你不知道你知道如何计算这些半径的具体半径)< / p>
public static double area(double radius) {
return Math.PI * radius * radius;
}
public static double circum(double radius) {
return 2 * radius * Math.PI;
}
然后,当您需要计算结果时,您可以调用这些方法:
System.out.println(" The Area of the Circle with radius " + radius + " is " + area(radius));
和
System.out.println("The Circumference of the Circle with radius " + radius + " is "
+ formatter.format(circum(radius)));