访问权限、对象使用

题目1

在作业5的基础上,再创建一个柱体类,包含矩形对象、高和体积等三个成员变量,一个构造方法进行成员变量初始化,和计算体积、换底两个功能方法,在主类中输入长、宽、高,计算柱体体积,输入新的长、宽、高,创建新的矩形对象,并利用换底方法换底,再次计算柱体体积。

import java.util.Scanner;
class juxing {//定义矩形类
aaa www;//成员变量
double high;
double mianji;
public juxing(aaa www,double high) {//构造方法
this.www=www;
this.high=high;
}
public void change_Www(aaa www) {//换底
this.www=www;
}
public double get_volume() {//求体积
mianji=high*www.getArea();
return mianji;
}

}
public class aaa {
double length;
double weight;
double area;
double perimeter;
public aaa(double length,double weight) {
this.length=length;
this.weight=weight;
}
public double getArea() {//面积
area=length*weight;
return area;
}
public double getPerimeter() {//周长
perimeter=2*(length+weight);
return perimeter;
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
double length=0.0, weight=0.0,high=0.0;
System.out.println("输入长、宽、高 :");
length=input.nextDouble();
weight=input.nextDouble();
high=input.nextDouble();//键盘获取值输入长宽高
aaa www=new aaa(length, weight);//声明对象
juxing qua=new juxing(www, high);
System.out.println("面积="+www.getArea());
System.out.println("周长="+www.getPerimeter());
System.out.println("体积="+qua.get_volume());
System.out.println("换底,输入长、宽:");
length=input.nextDouble();//输入换底后的数值
weight=input.nextDouble();
www=new aaa(length,weight);
qua.change_Www(www);
System.out.println("面积="+www.getArea());
System.out.println("周长="+www.getPerimeter());
System.out.println("体积="+qua.get_volume());
}
}

 

运行截图

 

 

 

题目2

设计名为MyInteger的类,它包括: int型数据域value 一个构造方法,当指定int值时,创建MyInteger对象 数据域value的访问器和修改器 isEven( )和isOdd( )方法,如果当前对象是偶数或奇数,返回true 类方法isPrime(MyInteger i),判断指定的值是否为素数,返回true 在主类中创建MyInteger对象,验证MyInteger类中各方法。

 

import java.util.*;
class MyInteger {
public int value;

 

public MyInteger(int value) {
this.value = value;
}

 

public int getValue() {//访问器
return value;
}

 

public void setValue(int value) {//修改器
this.value = value;
}

 

public boolean isEven() {//判断奇偶数
if (this.value % 2 == 0)
return true;
else
return false;
}

 

public boolean isOdd() {
if (this.value % 2 == 1)
return true;
else
return false;
}

 

public static boolean isPrime(MyInteger i) {//判断是否为素数
for (int j = 3; j < i.value; j++)
if (i.getValue() % j == 0)
return false;
return true;
}

 

public static void main(String[] args) {//主类
Scanner a=new Scanner(System.in);
System.out.println("请输入一个数:");
int value=a.nextInt();
MyInteger myInteger=new MyInteger(value);
System.out.println("该值为"+myInteger.getValue());
if(myInteger.isOdd())
System.out.println(myInteger.value+"是一个奇数");
if(myInteger.isEven())
System.out.println(myInteger.value+"是一个偶数");

System.out.println("再输入一个数");
value=a.nextInt();
myInteger.setValue(value);
if(myInteger.isPrime(myInteger))
System.out.println(myInteger.value+"是一个素数");
}
}

运行截图

 

 

 

 

posted @ 2019-09-22 15:56  l刘磊  阅读(102)  评论(0)    收藏  举报