题目1:
在作业5的基础上,再创建一个柱体类,包含矩形对象、高和体积等三个成员变量,一个构造方法进行成员变量初始化,和计算体积、换底两个功能方法,在主类中输入长、宽、高,计算柱体体积,输入新的长、宽、高,创建新的矩形对象,并利用换底方法换底,再次计算柱体体积。
代码:
volume.java:
package factorial; public class volume { public double high; public double getHigh() { return high; } public void setHigh(double high) { this.high = high; } public double getVolume(double high,double area) { double volume; volume = high * area; return volume; } }
Area.java:
package factorial; public class Area { public double length; public double width; public double getLength() { //访问器 return length; } public double getWidth() { return width; } public void setLength(double length) { //修改器 this.length = length; } public void setWidth(double width) { this.width = width; } public double getArea(double length,double width){ double area = length * width; return area; } }
rectangle.java:
import factorial.*; import java.util.*; public class rectangle { public static void main(String[] args) { System.out.println("请输入长和宽和高:"); Scanner input = new Scanner(System.in); Area p1 = new Area(); volume p2 = new volume(); p1.length = input.nextDouble(); p1.width = input.nextDouble(); p2.high = input.nextDouble(); double area1 = p1.getArea(p1.length, p1.width); System.out.println(p2.getVolume(p2.high, area1)); System.out.println("请输入新的长宽高:"); double newlength = input.nextDouble(); double newwidth = input.nextDouble(); double newhigh = input.nextDouble(); p1.setLength(newlength); p1.setWidth(newwidth); p2.setHigh(newhigh); double area2 = p1.getArea(newlength, newwidth); System.out.println(p2.getVolume(newhigh, area2)); } }
运行结果:
题目2:
设计名为MyInteger的类,它包括: int型数据域value 一个构造方法,当指定int值时,创建MyInteger对象 数据域value的访问器和修改器 isEven( )和isOdd( )方法,如果当前对象是偶数或奇数,返回true 类方法isPrime(MyInteger i),判断指定的值是否为素数,返回true 在主类中创建MyInteger对象,验证MyInteger类中各方法。
代码:
MyInteger.java:
package factorial; public class MyInteger { public int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public boolean isEven(int value) { if(value % 2 ==0) { return true; } else { return false; } } public boolean isOdd(int value) { if(value % 2 !=0) { return true; } else { return false; } } public boolean isPrime(int value) { for(int i = 2; i < value; i++) { if(value % i ==0) return false; } return true; } }
Test.java:
import java.util.*; import factorial.*; public class test { public static void main(String[] args) { System.out.println("请输入一个数"); Scanner input = new Scanner(System.in); MyInteger Test = new MyInteger(); int count = input.nextInt(); System.out.println("判断是否为偶数"+ Test.isEven(count)); System.out.println("判断是否为奇数" +Test.isOdd(count)); System.out.println("判断是否为质数" +Test.isPrime(count)); } }
运算结果: