JAVA创建一个Box类(长方体),在Box类中定义三个变量,分别表示长方体的长(length)、宽(width)和高(heigth)

编程创建一个Box类(长方体),在Box类中定义三个变量,分别表示长方体的长(length)、宽(width)和高(heigth),再定义一个方法void setBox(int l, int w, int h) 对这三个变量进行初始化,然后定义一个方法int volume ()来计算长方体的体积。最后,在main()方法中创建一个Box类的对象b,首先通过调用对象b的setBox()方法来设置长方体的长、宽和高,再通过调用对象b的volume() 方法来计算这个给定尺寸的长方体的体积,并输出这个结果。

package snippet;
import java.util.Scanner;
	public class Box{
    
    
		int length ;
		int width ;
		int height ;
	
	public  void setBox(int l,int w,int h){
    
    
		 length = l;
		 width =  w;
		 height = h;
	}
	public  int volume(){
    
    
	
	  return length * width * height;
	}

	public static void main(String[] args) {
    
    
		Box b = new Box();
		Scanner input = new Scanner(System.in);
		System.out.print("长:");
		int l = input.nextInt();
       System.out.print("宽:");
		int w = input.nextInt();
       System.out.print("高:");
		int h =input.nextInt();
		b.setBox(l, w, h);
		System.out.println("体积为:" + b.volume());
		
	}

}




猜你喜欢

转载自blog.csdn.net/qq_43952288/article/details/106926331