题目1:在作业5的基础上,再创建一个柱体类,包含矩形对象、高和体积等三个成员变量,一个构造方法进行成员变量初始化,和计算体积、换底两个功能方法,在主类中输入长、宽、高,计算柱体体积,输入新的长、宽、高,创建新的矩形对象,并利用换底方法换底,再次计算柱体体积。
jx代码(4个成员变量,一个方法,两个访问器,两个修改器)
package md;
import java.util.Scanner;
public class jx {
static int chang; //定义四个成员变量 长 ,宽,面积,周长
static int kuan;
static int area;
static int zc;
public int getChang(){ //访问器
return chang;
}
public void setChang(int chang){ //修改器
this.chang=chang;
}
public int getKuan(){ //访问器
return kuan;
}
public void setKuan(int kuan){ //修改器
this.kuan=kuan;
}
static int getArea(){ //求面积的方法
area=chang*kuan;
return area;
}
}
zt代码(三个成员变量,一个访问器,一个修改器,一个主方法)
package md;
import md.jx;
import java.util.Scanner;
public class zt {
static jx a;
static int height; // 三个成员变量
static int v;
public int getHeight(){
return height; //访问器
}
public void setHeight(){ //修改器
this.height=height;
}
public zt(jx a,int height,int v){
this.height=height;
v=a.area*height;
}
public static void main(String[] args) { //主方法
Scanner reader=new Scanner (System.in);
System.out.println("请输入长宽高"); //输入长宽高
height=reader.nextInt();
jx.chang=reader.nextInt();
jx.kuan=reader.nextInt();
v=a.getArea()*height;
System.out.println("体积是"+v); // 输出体积
System.out.println("修改 请输入新的长宽高"); //重新输入长宽高
height=reader.nextInt();
jx.chang=reader.nextInt();
jx.kuan=reader.nextInt();
v=a.getArea()*height;
System.out.println("新的体积是"+v); //输出新的体积
}
}
运行结果
题目2:设计名为MyInteger的类,它包括: int型数据域value 一个构造方法,当指定int值时,创建MyInteger对象 数据域value的访问器和修改器 isEven( )和isOdd( )方法,如果当前对象是偶数或奇数,返回true 类方法isPrime(MyInteger i),判断指定的值是否为素数,返回true 在主类中创建MyInteger对象,验证MyInteger类中各方法。
代码(一个类包含 : 构造方法,访问器,修改器,三个判断方法)
import java.util.Scanner;
public class Mylnteger {
//创建类 Mylnteger
private static final Mylnteger Mylnteger = null;
static int value;
public Mylnteger(int value){
//构造方法
Mylnteger.value=value;
}
public int getValue(){
//访问器
return value;
}
public void setValue(){
//修改器
this.value=value;
}
public static boolean isEven(){
//判断是否为奇数的方法
if(value!=0)
return true;
else
return false;
}
public static
//判断是否为偶数的方法
if(value%2==0)
return true;
else
return false;}
public static boolean isPrime(Mylnteger i){
//判断是否是素数的类方法
for(int j=2;j<i.value/2;j++){
if(i.value%j==0)
return false;
break;
}
return true ;
}
public static void main(String[] args) {
Scanner reader=new Scanner(System.in);
//引入scanner
Mylnteger dd;
//创建对象
dd=new Mylnteger(value);
System.out.println("请输入一个数");
dd.value=reader.nextInt();
//输入数进行判断
System.out.println(dd.value+"是否为偶数"+isOdd());
System.out.println(dd.value+"是否为奇数"+isEven());
System.out.println(dd.value+"是否为素数"+isPrime(dd));
System.out.println("请输入一个数");
dd.value=reader.nextInt();
//输入数进行判断
System.out.println(dd.value+"是否为偶数"+isOdd());
System.out.println(dd.value+"是否为奇数"+isEven());
System.out.println(dd.value+"是否为素数"+isPrime(dd));
}
}
运行结果