定义一个圆柱体类cylinder,并创建相应的对象,然后计算圆柱体的底面积与体积
输入
2.8
5
package com;
import java.util.*;
class cylinder
{
double radius;
int height;
double pi=3.14;
void area() {
System.out.println("底面积=" + pi * radius * radius);
}
double volume()
{
return (pi*radius*radius)*height;
}
}
public class sentence {
public static void main(String[] args) {
cylinder volu;
volu=new cylinder();
Scanner reader=new Scanner(System.in);
System.out.println("请输入圆柱的半径:");
volu.radius= reader.nextDouble();
System.out.println("请输入圆柱的高:");
volu.height=reader.nextInt();
System.out.println("低圆半径="+volu.radius);
System.out.println("圆柱的高="+volu.height);
System.out.print("圆柱");
volu.area();
System.out.println("圆柱体体积="+volu.volume());
}
}
以圆柱类cylinder为例在类内部调用自己的方法
import java.util.*;
class cylinder
{
double radius;
int height;
double pi=3.14;
double area() {
return pi * radius * radius;
}
double volume()
{
return area() * height;
}
}
public class sentence {
public static void main(String[] args) {
cylinder volu;
volu=new cylinder();
Scanner reader=new Scanner(System.in);
System.out.println("请输入圆柱的半径:");
volu.radius= reader.nextDouble();
System.out.println("请输入圆柱的高:");
volu.height=reader.nextInt();
System.out.println("低圆半径="+volu.radius);
System.out.println("圆柱的高="+volu.height);
System.out.print("圆柱");
System.out.println("底面积=" +volu.area());
System.out.println("圆柱体体积="+volu.volume());
}
}
进一步,如果要强调是对象本身的成员话,则可以在成员名前加this关键字。即this.成员名
this代表调用此成员的对象
double volume()
{
return this.area() * height;
}
在圆柱体类cylinder中用变量调用方法
class cylinder
{
double radius;
int height;
double pi=3.14;
void setcylinder(double r,int h,double p)
{
pi=p;
radius=r;
height=h;
}
double area() {
return pi * radius * radius;
}
double volume()
{
return this.area() * height;
}
}
public class sentence {
public static void main(String[] args) {
double r;int h;
cylinder volu;
volu=new cylinder();
Scanner reader=new Scanner(System.in);
System.out.println("请输入圆柱的半径:");
r=reader.nextDouble();
System.out.println("请输入圆柱的高:");
h=reader.nextInt();
volu.setcylinder( r, h,3.14);
System.out.println("低圆半径="+volu.radius);
System.out.println("圆柱的高="+volu.height);
System.out.print("圆柱");
System.out.println("底面积=" +volu.area());
System.out.println("圆柱体体积="+volu.volume());
}
}