Java初学者:变量范围问题
我正在练习我的java书中的一些工作,我在获取使用变量进行计算的方法时遇到了问题。请注意,这是一项正在进行的工作,我只是想让它使用circleArea方法来计算当前圆的面积。以下是必要的代码:Java初学者:变量范围问题,java,variables,methods,scope,Java,Variables,Methods,Scope,我正在练习我的java书中的一些工作,我在获取使用变量进行计算的方法时遇到了问题。请注意,这是一项正在进行的工作,我只是想让它使用circleArea方法来计算当前圆的面积。以下是必要的代码: public class Geometry { public static void printMenu() { System.out.println("This is a geometry calculator\nChoose what you would
public class Geometry
{
public static void printMenu()
{
System.out.println("This is a geometry calculator\nChoose what you would like to calculate" + "\n1. Find the area of a circle\n2. Find the area of a rectangle\n3."
+ " Find the area of a triangle\n4. Find the circumference of a circle."
+ "\n5. Find the perimeter of a rectangle\n6. Find the perimeter of a triangle"
+ "\nEnter the number of your choice:");
}
public static void circleArea(double area)
{
System.out.println(Math.PI*Math.pow(radius, 2));
}
public static void main(String[] args)
{
int choice; //the user's choice
double value = 0; //the value returned from the method
char letter; //the Y or N from the user's decision to exit
double radius; //the radius of the circle
double length; //the length of the rectangle
double width; //the width of the rectangle
double height; //the height of the triangle
double base; //the base of the triangle
double side1; //the first side of the triangle
double side2; //the second side of the triangle
double side3; //the third side of the triangle
}
}
请声明类的变量并从中调用函数
public class Geometry
{
int choice; //the user's choice
double value = 0; //the value returned from the method
char letter; //the Y or N from the user's decision to exit
double radius; //the radius of the circle
double length; //the length of the rectangle
double width; //the width of the rectangle
double height; //the height of the triangle
double base; //the base of the triangle
double side1; //the first side of the triangle
double side2; //the second side of the triangle
double side3; //the third side of the triangle
public static void printMenu()
{
System.out.println("This is a geometry calculator\nChoose what you would like to calculate"
+ "\n1. Find the area of a circle\n2. Find the area of a rectangle\n3."
+ " Find the area of a triangle\n4. Find the circumference of a circle."
+ "\n5. Find the perimeter of a rectangle\n6. Find the perimeter of a triangle"
+ "\nEnter the number of your choice:");
}
public static void circleArea(double area)
{
System.out.println(Math.PI*Math.pow(radius, 2));
}
public static void main(String[] args)
{
Geometry g = new Geometry();
g.printMenu();
}
}
你到底遇到了什么问题?任何声明到main中的变量都不能通过类中的其他函数访问。家庭作业问题在这里通常做得不好,但一个明显的问题是你的
circleArea
将area
作为参数,而不是作为结果返回它public static double circleArea(双半径)
更像您想要的声明(尽管在您当前的代码中,您只是发出结果,而不是返回结果,因此如果您想这样做,您可以保持无效)。这不是家庭作业,只是为了个人练习。使用的变量是本书提供的变量。我想我只是想知道如何让我的方法处理半径变量。我想我理解你在做什么,但我不认为这是我的书想要我做的。我是否将该方法放错了位置?您在一个函数中声明了变量,并试图从另一个函数访问。一个函数中声明的任何变量都不能在另一个函数中访问。