题目1:
在作业5的基础上,再创建一个柱体类,包含矩形对象、高和体积等三个成员变量,一个构造方法进行成员变量初始化,和计算体积、换底两个功能方法,在主类中输入长、宽、高,计算柱体体积,输入新的长、宽、高,创建新的矩形对象,并利用换底方法换底,再次计算柱体体积。
代码:
1.juxing类
/** 3个人成员变量 3个方法*
**/width和length对应的访问器和修改器 一个计算矩形面积的方法
public class juxing { public int width; public int length; public int area; public int getWidth() {//width的访问器 return width; } public void setWidth(int width) {//width的修改器 this.width = width; } public int getLength() {//length的访问器 return length; } public void setLength(int length) {//length的修改器 this.length = length; } public int getarea(int length,int width){//计算矩形面积的方法 this.length=length; this.width=width; this.area=length*width; return area; } }
2.lengzhu
/** 3个成员变量 4个方法
* hight的访问器和修改器 一个有参的构造方法 1个计算底面积的方法 修改底的方法
**/
public class lengzhu { juxing j; int hight; int V; public int getHight() {//higth的访问器 return hight; } public void setHight(int hight) {//hight的修改器 this.hight = hight; } lengzhu(juxing j,int hight){//有参的构造方法 this.j=j; this.hight=hight; } void countV(juxing j){//计算体积 V=hight*j.getarea(j.length, j.width); System.out.print("四棱柱的体积是"+V); } void change(int width,int length){//修改底面积 this.j.width=width; this.j.length=length; } }
3.Text
/**2个对象 5个int型的数
*在主类中输入长、宽、高,计算柱体体积,输入新的长、宽、高,创建新的矩形对象,并利用换底方法换底,再次计算柱体体积。
**/
import java.util.Scanner; public class Text { public static void main(String[] args) { Scanner reader=new Scanner(System.in);//创建reader的对象 juxing j=new juxing(); j.length=reader.nextInt();//输入底的长 j.width=reader.nextInt();//输入底的宽 int hight=reader.nextInt();//输入柱形的改 lengzhu l=new lengzhu(j,hight); l.countV(j);//调用计算体积的方法 int a=reader.nextInt(); int b=reader.nextInt(); l.change(a, b);//修改底的长宽 //int h=reader.nextInt(); l.setHight(reader.nextInt());//修改高 l.countV(j); } }
运行截图
题目2:
设计名为MyInteger的类,它包括: int型数据域value 一个构造方法,当指定int值时,创建MyInteger对象 数据域value的访问器和修改器 isEven( )和isOdd( )方法,如果当前对象是偶数或奇数,返回true 类方法isPrime(MyInteger i),判断指定的值是否为素数,返回true 在主类中创建MyInteger对象,验证MyInteger类中各方法。
代码:
1.MyInteger
/**1个成员变量 7个方法
*int型 value 一个无参构造方法 一个有参的构造方法 value的访问器和修改器 isEven( )和isOdd( )方法,如果当前对象是偶数或奇数,返回true 方法isPrime(MyInteger i),判断指定的值是否为素数,返回true
**/
package com; class MyInteger { int value; public int getValue() {//value的访问器 return value; } public void setValue(int value) {//value的修改器 this.value = value; } public MyInteger() {//无参的构造法 } MyInteger(int value){//有参的构造方法 this.value=value; } boolean isEven(){//是否为偶数 if(value%2==0)return true; else return false; } boolean isOdd(){//是否为基数 if(value%2==1)return true; else return false; } boolean isPrime(MyInteger i){//是否为质数 for(int j=2;j<i.value;j++){ if(i.value%j==0){ return false; } } return true; } }
2.text
/** 在主类中创建MyInteger对象,验证MyInteger类中各方法。
*
**/
package com; public class Text { public static void main(String[] args) { MyInteger m=new MyInteger(6); System.out.println(m.value+"是否是偶数"+m.isEven()); System.out.println(m.value+"是否是基数"+m.isOdd()); System.out.println(m.value+"是否是质数"+m.isPrime(m)); } }