第7次作业--访问权限、对象使用
题目一
在作业5的基础上,再创建一个柱体类,包含矩形对象、高和体积等三个成员变量,一个构造方法进行成员变量初始化,和计算体积、换底两个功能方法,在主类中输入长、宽、高,计算柱体体积,输入新的长、宽、高,创建新的矩形对象,并利用换底方法换底,再次计算柱体体积。
代码
1 package aaa; 2 3 public class Rectangle { 4 int length; 5 int widle; 6 int area; 7 public int getlength(){ 8 return length; 9 } 10 public void setlength(int length){ 11 this.length=length; 12 13 } 14 public int getwidle(){ 15 return widle; 16 } 17 public void setwidle(int widle){ 18 this.widle=widle; 19 } 20 public int getarea(int length,int widle){ 21 area=length*widle; 22 return area; 23 } 24 25 26 }
1 package aaa; 2 3 public class barrle { 4 Rectangle A=new Rectangle(); 5 int height; 6 public int getheight() { 7 return height; 8 } 9 public void setheight(int height) { 10 this.height = height; 11 } 12 int getV(int area,int height){ 13 int V=area*height; 14 return V; 15 } 16 17 }
1 package aaa; 2 import java.util.Scanner; 3 4 public class prime { 5 public static void main(String[] args) { 6 Rectangle A=new Rectangle(); 7 barrle B=new barrle(); 8 System.out.println("请输入柱体的长宽高"); 9 Scanner C=new Scanner(System.in); 10 A.length=C.nextInt(); 11 A.widle=C.nextInt(); 12 B.height=C.nextInt(); 13 System.out.println("柱体的体积为:"+B.getV(A.getarea(A.length,A.widle),B.height)); 14 System.out.println("请输入换底的长和宽"); 15 Scanner d=new Scanner(System.in); 16 A.length=d.nextInt(); 17 A.widle=d.nextInt(); 18 System.out.println("换底之后的体积是:"+B.getV(A.getarea(A.length,A.widle),B.height)); 19 20 21 } 22 23 }
题目2:
设计名为MyInteger的类,它包括: int型数据域value 一个构造方法,当指定int值时,创建MyInteger对象 数据域value的访问器和修改器 isEven( )和isOdd( )方法,如果当前对象是偶数或奇数,返回true 类方法isPrime(MyInteger i),判断指定的值是否为素数,返回true 在主类中创建MyInteger对象,验证MyInteger类中各方法。
1 package aaaaaa; 2 3 public class MyInteger { 4 int value; //创建value成员变量并设置value的访问器和修改器 5 public int getValue() { 6 return value; 7 } 8 public void setValue(int value) { 9 this.value = value; 10 } 11 MyInteger my; //创建my对象 12 13 boolean isEven(){ //判断是否为偶数 14 if(value%2==0){ 15 return true; 16 } 17 return false; 18 } 19 boolean isOdd(){ //判断是否为奇数 20 if(value%2!=0){ 21 return true; 22 } 23 return false; 24 } 25 public static boolean isPrime(int i){ //判断是否为素数 26 27 28 for (int j=2;j<Math.sqrt(i);j++){ 29 if(i%j==0){ 30 return false; 31 } 32 else return false; 33 34 35 } 36 } 37 } 38
package ccc; import java.util.Scanner; public class Test { public static void main(String[] args) { Zhuti zhu=new Zhuti(); Rectangle re = new Rectangle(); Scanner sc=new Scanner(System.in); System.out.println("请输入柱体的长宽高:"); re.length=sc.nextInt(); re.width=sc.nextInt(); zhu.height=sc.nextInt(); System.out.println("柱体体积为:"+zhu.getVolume(re.getArea(re.length, re.width),zhu.height)); System.out.println("请输入新矩形的长和宽:"); re.length=sc.nextInt(); re.width=sc.nextInt(); System.out.println("换底之后的体积为:"+zhu.getVolume(zhu.ChangeDi(re.length, re.width),zhu.height)); } }