前言
本篇作为个人的java复习,部分代码有参考其他博客。
6-1 设计一个矩形类Rectangle
设计一个名为Rectangle的类表示矩形。这个类包括:
两个名为width和height的double型数据域,它们分别表示矩形的宽和高。width和height的默认值都为1.
一个无参构造方法。
一个为width和height指定值的矩形构造方法。
一个名为getArea()的方法返回这个矩形的面积。
一个名为getPerimeter()的方法返回这个矩形的周长。
类名为:Rectangle
裁判测试程序样例:
import java.util.Scanner;
/* 你的代码将被嵌入到这里 */
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double w = input.nextDouble();
double h = input.nextDouble();
Rectangle myRectangle = new Rectangle(w, h);
System.out.println(myRectangle.getArea());
System.out.println(myRectangle.getPerimeter());
input.close();
}
}
输入样例:
3.14 2.78
输出样例:
8.7292
11.84
题解:
class Rectangle{
private double width;
private double height;
public Rectangle(){
this.width = 1;
this.height=1;
}
public Rectangle(double width,double height){
this.width = width;
this.height= height;
}
public double getArea(){
return width*height;
}
public double getPerimeter(){
return 2*(width+height);
}
}
6-2 根据派生类写出基类(Java)
裁判测试程序样例中展示的是一段定义基类People
、派生类Student
以及测试两个类的相关Java代码,其中缺失了部分代码,请补充完整,以保证测试程序正常运行。
函数接口定义:
提示:
观察派生类代码和main方法中的测试代码,补全缺失的代码。
裁判测试程序样例:
注意:真正的测试程序中使用的数据可能与样例测试程序中不同,但仅按照样例中的格式调用相关方法(函数)。
class People{
protected String id;
protected String name;
/** 你提交的代码将被嵌在这里(替换此行) **/
}
class Student extends People{
protected String sid;
protected int score;
public Student() {
name = "Pintia Student";
}
public Student(String id, String name, String sid, int score) {
super(id, name);
this.sid = sid;
this.score = score;
}
public void say() {
System.out.println("I'm a student. My name is " + this.name + ".");
}
}
public class Main {
public static void main(String[] args) {
Student zs = new Student();
zs.setId("370211X");
zs.setName("Zhang San");
zs.say();
System.out.println(zs.getId() + " , " + zs.getName());
Student ls = new Student("330106","Li Si","20183001007",98);
ls.say();
System.out.println(ls.getId() + " : " + ls.getName());
People ww = new Student();
ww.setName("Wang Wu");
ww.say();
People zl = new People("370202", "Zhao Liu");
zl.say();
}
}
输入样例:
在这里给出一组输入。例如:
(无)
输出样例:
在这里:给出相应的输出。例如:
I'm a student. My name is Zhang San.
370211X , Zhang San
I'm a student. My name is Li Si.
330106 : Li Si
I'm a student. My name is Wang Wu.
I'm a person! My name is Zhao Liu.
题解:
public String getId(){
return id;
}
public String setId(String id){
return this.id=id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public People(){
}
public People(String id,String name) {
this.id=id;
this.name=name;
}
public void say(){
System.out.print("I'm a person! My name is " + this.name + ".");
}
6-3 写出派生类构造方法(Java)
裁判测试程序样例中展示的是一段定义基类People
、派生类Student
以及测试两个类的相关Java代码,其中缺失了部分代码,请补充完整,以保证测试程序正常运行。
函数接口定义:
提示: 观察类的定义和main方法中的测试代码,补全缺失的代码。
裁判测试程序样例:
注意:真正的测试程序中使用的数据可能与样例测试程序中不同,但仅按照样例中的格式调用相关方法(函数)。
裁判测试程序样例中展示的是一段定义基类People、派生类Student以及测试两个类的相关Java代码,其中缺失了部分代码,请补充完整,以保证测试程序正常运行。
函数接口定义:
提示:
观察类的定义和main方法中的测试代码,补全缺失的代码。
裁判测试程序样例:
注意:真正的测试程序中使用的数据可能与样例测试程序中不同,但仅按照样例中的格式调用相关方法(函数)。
class People{
private String id;
private String name;
public People(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
class Student extends People{
private String sid;
private int score;
public Student(String id, String name, String sid, int score) {
/** 你提交的代码将被嵌在这里(替换此行) **/
}
public String toString(){
return ("(Name:" + this.getName()
+ "; id:" + this.getId()
+ "; sid:" + this.sid
+ "; score:" + this.score
+ ")");
}
}
public class Main {
public static void main(String[] args) {
Student zs = new Student("370202X", "Zhang San", "1052102", 96);
System.out.println(zs);
}
}
输入样例:
在这里给出一组输入。例如:
(无)
输出样例:
(Name:Zhang San; id:370202X; sid:1052102; score:96)
输入样例:
在这里给出一组输入。例如:
(无)
输出样例:
(Name:Zhang San; id:370202X; sid:1052102; score:96)
题解:
super(id,name);
this.sid=sid;
this.score=score;
6-4 重写父类方法equals
在类Student中重写Object类的equals方法。使Student对象学号(id)相同时判定为同一对象。
函数接口定义:
在类Student中重写Object类的equals方法。使Student对象学号(id)相同时判定为同一对象。
裁判测试程序样例:
import java.util.Scanner;
class Student {
int id;
String name;
int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
/* 请在这里填写答案 */
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Student s1 = new Student(sc.nextInt(),sc.next(),sc.nextInt());
Student s2 = new Student(sc.nextInt(),sc.next(),sc.nextInt());
System.out.println(s1.equals(s2));
sc.close();
}
}
输入样例:
1001 Peter 20
1001 Jack 18
输出样例:
true
题解
public boolean equals(Object o){
if(this==o){
return true;
}if(o instanceof Student){
Student s=(Student)o;//把传入的对象转换为Student
return this.id==s.id;//id相同则返回true
}else {
return false;
}
}
6-5 从抽象类shape类扩展出一个圆形类Circle
请从下列的抽象类shape类扩展出一个圆形类Circle,这个类圆形的半径radius作为私有成员,类中应包含初始化半径的构造方法。
public abstract class shape {// 抽象类
public abstract double getArea();// 求面积
public abstract double getPerimeter(); // 求周长
}
主类从键盘输入圆形的半径值,创建一个圆形对象,然后输出圆形的面积和周长。保留4位小数。
圆形类名Circle
裁判测试程序样例:
import java.util.Scanner;
import java.text.DecimalFormat;
abstract class shape {// 抽象类
/* 抽象方法 求面积 */
public abstract double getArea( );
/* 抽象方法 求周长 */
public abstract double getPerimeter( );
}
/* 你提交的代码将被嵌入到这里 */
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat d = new DecimalFormat("#.####");// 保留4位小数
double r = input.nextDouble( );
shape c = new Circle(r);
System.out.println(d.format(c.getArea()));
System.out.println(d.format(c.getPerimeter()));
input.close();
}
}
输入样例:
3.1415926
输出样例:
31.0063
19.7392
题解:
class Circle extends shape{
private double radius;
public Circle(double r){
radius=r;
}
public double getArea(){
return Math.PI*radius*radius;
}
public double getPerimeter(){
return 2*Math.PI*radius;
}
}
6-6 创建一个直角三角形类实现IShape接口
创建一个直角三角形类(regular triangle)RTriangle类,实现下列接口IShape。两条直角边长作为RTriangle类的私有成员,类中包含参数为直角边的构造方法。
interface IShape {// 接口
public abstract double getArea(); // 抽象方法 求面积
public abstract double getPerimeter(); // 抽象方法 求周长
}
###直角三角形类的定义:
直角三角形类的构造函数原型如下:
RTriangle(double a, double b);
其中 a
和 b
都是直角三角形的两条直角边。
裁判测试程序样例:
import java.util.Scanner;
import java.text.DecimalFormat;
interface IShape {
public abstract double getArea();
public abstract double getPerimeter();
}
/*你写的代码将嵌入到这里*/
public class Main {
public static void main(String[] args) {
DecimalFormat d = new DecimalFormat("#.####");
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
IShape r = new RTriangle(a, b);
System.out.println(d.format(r.getArea()));
System.out.println(d.format(r.getPerimeter()));
input.close();
}
}
输入样例:
3.1 4.2
输出样例:
6.51
12.5202
class RTriangle implements IShape{
private double a,b;
public RTriangle(double a, double b){
this.a=a;
this.b=b;
}
public double getArea(){
return a*b*0.5;
}
public double getPerimeter(){
return a+b+Math.sqrt(a*a+b*b);
}
}
6-7 jmu-Java-06异常-多种类型异常的捕获
如果try块中的代码有可能抛出多种异常,且这些异常之间可能存在继承关系,那么在捕获异常的时候需要注意捕获顺序。
补全下列代码,使得程序正常运行。
裁判测试程序:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String choice = sc.next();
try {
if (choice.equals("number"))
throw new NumberFormatException();
else if (choice.equals("illegal")) {
throw new IllegalArgumentException();
} else if (choice.equals("except")) {
throw new Exception();
} else
break;
}
/*这里放置你的答案*/
}//end while
sc.close();
}
###输出说明
在catch
块中要输出两行信息:
第1行:要输出自定义信息。如下面输出样例的number format exception
第2行:使用System.out.println(e)
输出异常信息,e是所产生的异常。
输入样例
number illegal except quit
输出样例
number format exception
java.lang.NumberFormatException
illegal argument exception
java.lang.IllegalArgumentException
other exception
java.lang.Exception
题解
catch(NumberFormatException e){
System.out.println("number format exception");
System.out.println(e);
}
catch(IllegalArgumentException e){
System.out.println("illegal argument exception");
System.out.println(e);
}
catch(Exception e){
System.out.println("other exception");
System.out.println(e);
}
6-8 jmu-Java-03面向对象基础-Object
输入整数n,创建n个对象,放入同一个数组中。
如果输入c
,则new Computer();
//注意:Computer是系统中已有的类,无需自己编写
如果输入d
,则根据随后的输入创建Double
类型对象。
如果输入i
,则根据随后的输入创建Integer
类型对象。
如果输入s
,则根据随后的输入创建String
类型对象。
如果不是以上这些输入,则不创建对象,而是将null
存入数组相应位置。
最后倒序输出数组中的所有对象,如果数组中相应位置的元素为null
则不输出。
裁判测试程序:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//这边是你的代码
sc.close();
}
输入样例:
5
c
d 2.3
other
i 10
s Test
输出样例:
Test
10
2.3
//这行显示Computer对象toString方法
题解
int n=sc.nextInt();
Object a[]=new Object[n];
for(int i=0;i<n;i++) {
String s=sc.next();
if(s.equals("c")) {
a[i]=new Computer();
}else if(s.equals("d")) {
a[i]=new Double(sc.nextDouble());
}else if(s.equals("i")) {
a[i]=new Integer(sc.nextInt());
}else if(s.equals("s")) {
a[i]=new String(sc.next());
}else {
a[i]=null;
}
}
for(int i=n-1;i>=0;i--) {
if(a[i] instanceof String) {
System.out.println(a[i].toString());
}else if(a[i] instanceof Integer) {
System.out.println(a[i].toString());
}else if(a[i] instanceof Double) {
System.out.println(a[i].toString());
}else if(a[i] instanceof Computer) {
System.out.println(a[i].toString());
}else {
}
}
6-9 人口统计
本题运行时要求键盘输入10个人员的信息(每一个人信息包括:姓名,性别,年龄,民族),要求同学实现一个函数,统计民族是“汉族”的人数。
函数接口定义:
public static int numofHan(String data[])
其中 data[]
是传入的参数。 data[]
中的每一个元素都是一个完整的人员信息字符串,该字符串由“姓名,性别,年龄,民族”,各项之间用英文半角的逗号分隔。函数须返回 值是汉族的人数。
裁判测试程序样例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final int HUMANNUM=10;
String persons[]=new String[HUMANNUM];
Scanner in=new Scanner(System.in);
for(int i=0;i<persons.length;i++)
persons[i]=in.nextLine();
int result=numofHan(persons);
System.out.println(result);
}
/*在此处给出函数numofHan()*/
}
输入样例:
Tom_1,男,19,汉族
Tom_2,女,18,汉族
Tom_3,男,20,满族
Tom_4,男,18,汉族
Tom_5,男,19,汉族人
Tom_6,女,17,汉族
Tom_7,男,19,蒙古族
汉族朋友_1,男,18,汉族
Tom_8,male,19,老外
Tom_9,female,20,汉族
输出样例:
7
题解 :
public static int numofHan(String data[]){
int count=0;//定义整形变量
for(int i=0;i<data.length;i++)//遍历整个字符串数组
{
if(data[i].indexOf("汉",4)>0)//indexOf方法可以获取到一个字符串中指定字符的位置,例如从字符串第7个字符开始,查找”汉“,找不到返回-1
{
count++;
}
}
return count;
}
6-10 jmu-Java-05集合-List中指定元素的删除
编写以下两个函数
//以空格(单个或多个)为分隔符,将line中的元素抽取出来,放入一个List
public static List<String> convertStringToList(String line)
//在list中移除掉与str内容相同的元素
public static void remove(List<String> list, String str)
裁判测试程序:
public class Main {
/*covnertStringToList函数代码*/
/*remove函数代码*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
List<String> list = convertStringToList(sc.nextLine());
System.out.println(list);
String word = sc.nextLine();
remove(list,word);
System.out.println(list);
}
sc.close();
}
}
样例说明:底下展示了4组测试数据。
输入样例
1 2 1 2 1 1 1 2
1
11 1 11 1 11
11
2 2 2
1
1 2 3 4 1 3 1
1
输出样例
[1, 2, 1, 2, 1, 1, 1, 2]
[2, 2, 2]
[11, 1, 11, 1, 11]
[1, 1]
[2, 2, 2]
[2, 2, 2]
[1, 2, 3, 4, 1, 3, 1]
[2, 3, 4, 3]
题解
public static List<String> convertStringToList(String line) {
List<String> a=new ArrayList<String>();
String s[]=line.split("\\s+");
for(int i=0;i<s.length;i++) {
a.add(s[i]);
}
return a;
}
public static void remove(List<String> list, String str) {
for(int i=0;i<list.size();) {
if(list.get(i).equals(str)) {
list.remove(i);
i=0;
}else {
i++;
}
}
}
6-11 jmu-Java-07多线程-Thread
编写MyThread类继承自Thread
。创建MyThread类对象时可指定循环次数n。
功能:输出从0到n-1的整数。 并在最后使用System.out.println(Thread.currentThread().getName()+" "+isAlive())
打印标识信息
裁判测试程序:
import java.util.Scanner;
/*这里放置你的答案,即MyThread类的代码*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Thread t1 = new MyThread(Integer.parseInt(sc.next()));
t1.start();
}
}
输入样例:
3
输出样例:
0
1
2
标识信息
题解:
class MyThread extends Thread {
private int n;
public MyThread(int n) {
this.n = n;
}
public void run() {
for (int i = 0; i < n; i++) {
System.out.println(i);
}
System.out.println(Thread.currentThread().getName() + " " + isAlive());
}
}
6-12 jmu-Java-07多线程-PrintTask
编写PrintTask类实现Runnable
接口。
功能:输出从0到n-1的整数(n在创建PrintTask对象的时候指定)。并在最后使用System.out.println(Thread.currentThread().getName());
输出标识信息。
裁判测试程序:
import java.util.Scanner;
/*这里放置你的答案,即PrintTask类的代码*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintTask task = new PrintTask(Integer.parseInt(sc.next()));
Thread t1 = new Thread(task);
t1.start();
sc.close();
}
}
输入样例:
3
输出样例:
0
1
2
标识信息
题解
class PrintTask implements Runnable{
private int n;
public PrintTask(int n){
this.n=n;
}
public void run(){
for(int i=0;i<n;i++){
System.out.println(i);
}
System.out.println(Thread.currentThread().getName());
}
}
6-13 jmu-Java-03面向对象基础-覆盖与toString
有Person
类,Company
类,Employee
类。
其中Employee类继承自Person类,属性为:
private Company company;
private double salary;
现在要求编写Employee类的toString
方法,返回的字符串格式为:父类的toString-company的toString-salary
函数接口定义:
public String toString()
输入样例:
输出样例:
Li-35-true-MicroSoft-60000.0
题解
public String toString(){
return super.toString()+"-"+company.toString()+"-"+salary;
}
6-14 学生、大学生、研究生类
定义Student学生类,拥有学号、姓名、性别属性,提供构造函数,以及相应属性的get set函数,提供函数attendClass(String className)表示上课。
定义CollegeStudent大学生类继承自Student类,拥有新增属性专业,提供构造函数,提供新增属性的get和set函数
定义GraduateStudent研究生类继承自CollegeStudent类,拥有新增属性导师,提供构造函数,提供新增属性的get和set函数,提供函数doResearch() 表示做研究(打印xx is doing research)。
main函数中对构造的类进行测试
输入描述:
学生类信息,学号、姓名、性别
大学生类信息,学号、姓名、性别、专业
研究生类信息,学号、姓名、性别、专业、导师
输出描述:
学生类信息
大学生类信息
研究生类信息
裁判测试程序样例:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int no = scan.nextInt();
String name = scan.next();
String sex = scan.next();
Student s = new Student(no, name, sex);
s.print();
no = scan.nextInt();
name = scan.next();
sex = scan.next();
String major = scan.next();
CollegeStudent c = new CollegeStudent(no, name, sex, major);
c.print();
no = scan.nextInt();
name = scan.next();
sex = scan.next();
major = scan.next();
String supervisor = scan.next();
GraduateStudent g = new GraduateStudent(no, name, sex, major, supervisor );
g.print();
g.doResearch();
scan.close();
}
}
/* 你的代码被嵌在这里*/
输入样例:
在这里给出一组输入。例如:
1 liu female
2 chen female cs
3 li male sc wang
输出样例:
在这里给出相应的输出。例如:
no: 1
name: liu
sex: female
no: 2
name: chen
sex: female
major: cs
no: 3
name: li
sex: male
major: sc
supervisor: wang
li is doing research
题解
class Student{
private int id;
private String name ,sex;
public Student(int id ,String name,String sex){
this.id=id;
this.name=name;
this.sex=sex;
}
public String getName() {
return this.name;
}
public void print(){
System.out.println("no: "+this.id);
System.out.println("name: "+this.name);
System.out.println("sex: "+this.sex);
}
}
class CollegeStudent extends Student{
private String major;
public CollegeStudent(int id,String name ,String sex,String major){
super(id,name,sex);
this.major=major;
}
public void print(){
super.print();
System.out.println("major: "+this.major);
}
}
class GraduateStudent extends CollegeStudent{
private String supervisor;
public GraduateStudent (int id,String name ,String sex,String major,String supervisor){
super(id,name,sex,major);
this.supervisor=supervisor;
}
public void print(){
super.print();
System.out.println("supervisor: "+this.supervisor);
}
public void doResearch(){
System.out.println(this.getName()+" is doing research");
}
}
6-15 Shape类
定义一个形状类Shape,提供计算周长getPerimeter()和面积getArea()的函数
定义一个子类正方形类Square继承自Shape类,拥有边长属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()
定义一个子类长方形类Rectangle继承自Square类,拥有长、宽属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()
定义一个子类圆形类Circle继承自Shape,拥有半径属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()
在main函数中,分别构造三个子类的对象,并输出他们的周长、面积.
提示:用System.out.printf("%.2f",d)进行格式化输出
输入描述:
正方形类的边长
长方形类的长宽
圆类的半径
输出描述:
正方形的周长、面积
长方形的周长、面积
裁判测试程序样例:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double length = scan.nextDouble();
Square s = new Square(length);
System.out.printf("%.2f ",s.getPerimeter());
System.out.printf("%.2f\n",s.getArea());
length = scan.nextDouble();
double wide = scan.nextDouble();
Rectangle r = new Rectangle(length,wide);
System.out.printf("%.2f ",r.getPerimeter());
System.out.printf("%.2f\n",r.getArea());
double radius = scan.nextDouble();
Circle c = new Circle(radius);
System.out.printf("%.2f ",c.getPerimeter());
System.out.printf("%.2f\n",c.getArea());
scan.close();
}
}
/* 你的代码被嵌在这里 */
输入样例:
在这里给出一组输入。例如:
1
1 2
2
输出样例:
在这里给出相应的输出。例如:
4.00 1.00
6.00 2.00
12.57 12.57
abstract class Shape{
abstract double getPerimeter();
abstract double getArea();
}
class Square extends Shape{
double length;
public Square(double length){
this.length =length;
}
public double getPerimeter(){
return 4*length;
}
public double getArea(){
return length*length;
}
}
class Rectangle extends Square{
double width ;
public Rectangle(double length ,double width){
super(length);
this.width=width ;
}
public double getPerimeter(){
return 2*(length+width);
}
public double getArea(){
return length*width;
}
}
class Circle extends Shape{
double r;
public Circle(double r){
this.r=r;
}
public double getPerimeter(){
return 2*Math.PI*r;
}
public double getArea(){
return Math.PI*r*r;
}
}
6-16 长方形长方体类
定义一个长方形类Rectangle,拥有长、宽属性,提供构造函数,能够计算周长getPerimeter()和面积getArea()
定义一个子类长方体类,拥有长、宽、高属性,提供构造函数,getPerimeter函数计算所有边的周长,getArea函数计算表面积,新增getVolume函数,计算体积
在main函数中,分别构造长方形类和长方体类的对象,并输出他们的周长、面积、体积,保留两位小数
输入描述:
长方形类的长、宽
长方体类的长、宽、高
输出描述:
长方形的周长和面积
长方体的周长,表面积,体积
裁判测试程序样例:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double length = scan.nextDouble();
double wide = scan.nextDouble();
Rectangle r = new Rectangle(length,wide);
System.out.printf("%.2f ",r.getPerimeter());
System.out.printf("%.2f",r.getArea());
System.out.println();
length = scan.nextDouble();
wide = scan.nextDouble();
double height = scan.nextDouble();
Cuboid c = new Cuboid (length, wide, height);
System.out.printf("%.2f ",c.getPerimeter());
System.out.printf("%.2f ",c.getArea());
System.out.printf("%.2f",c.getVolume());
scan.close();
}
}
/* 你的代码被嵌在这里 */
输入样例:
在这里给出一组输入。例如:
1 2
1 2 3
输出样例:
在这里给出相应的输出。例如:
6.00 2.00
24.00 22.00 6.00
题解:
class Rectangle{
private double l,w;
public Rectangle(double l,double w){
this.l=l;
this.w=w;
}
public double getPerimeter(){
return 2*(l+w);
}
public double getArea(){
return l*w;
}
}
class Cuboid {
private double h,l1,w1;
public Cuboid(double l1,double w1,double h){
this.l1=l1;
this.w1=w1;
this.h=h;
}
public double getPerimeter(){
return 4*(l1+w1+h);
}
public double getArea(){
return 2*(l1*w1+w1*h+h*l1);
}
public double getVolume(){
return l1*w1*h;
}
}
6-17 圆柱体计算
单位 浙江工商大学杭州商学院
1.构造一个Circle类:
1)该类有一个double型成员变量radius存放半径;
2)该类有一个有参构造方法,为成员变量radius赋值;
3)该类具有getArea和getLength两个方法,能够利用半径和Math.PI计算高精度的面积和周长。
2.构造一个Column类:
1)该类有一个Circle型成员变量bottom为圆柱体的底面;
2)该类有一个double型成员变量height存放圆柱体的高;
3)该类有getBottom和setBottom方法作为成员变量bottom的访问方法和赋值方法;
4)该类有getHeight和setHeight方法作为成员变量height的访问方法和赋值方法;
5)该类有getVolume方法,计算并返回圆柱体的体积。
裁判测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
double r=scanner.nextDouble();
double h=scanner.nextDouble();
Circle c = new Circle(r);
Column column=new Column();
column.setBottom(c);
column.setHeight(h);
System.out.printf("底面面积和周长分别为:%.2f %.2f\n",column.getBottom().getArea(),column.getBottom().getLength());
System.out.printf("体积为:%.2f\n",column.getVolume());
scanner.close();
}
}
/* 请在这里填写答案 */
输入样例:
在这里给出一组输入。例如:
10 2
输出样例:
在这里给出相应的输出。例如:
底面面积和周长分别为:314.16 62.83
体积为:628.32
题解:
class Circle{
private double radius;
public Circle(double r){
this.radius=r;
}
public double getArea(){
return Math.PI*radius*radius;
}
public double getLength(){
return 2.0*Math.PI*radius;
}
}
class Column {
private Circle bottom;
private double height;
public void setBottom(Circle bottom){
this.bottom=bottom;
}
public void setHeight(double height){
this.height=height;
}
public double getHeight() {
return height;
}
public Circle getBottom() {
return bottom;
}
public double getVolume(){
return bottom.getArea()*height;
}
}
6-18 Book类设计
Book类设计
创建一个书籍类:Book类:
(1)string name、 int price的私有成员
(2)包含有参构造方法和无参构造方法
(3)成员方法public void printInfo()
裁判测试程序样例中展示的是测试类的相关Java代码,其中缺失了部分代码,请补充完整,以保证测试程序正常运行。
裁判测试程序样例:
import java.util.Scanner;
/* 请在这里补充代码 */
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = in.next();
int price = in.nextInt();
Book book1 = new Book(name,price);
Book book2 = new Book();
book1.printInfo();
book2.printInfo();
in.close();
}
}
输入样例:
C语言程序设计 46
输出样例:
在这里给出相应的输出。例如:
C语言程序设计-46
Java程序设计-54
题解:
class Book{
private String name ;
private int price;
public Book(){
this.name ="Java程序设计";
this.price=54;
}
public Book(String name,int price){
this.name=name;
this.price =price ;
}
public void printInfo(){
System.out.println(this.name+'-'+this.price);
}
}
6-19 Flower类设计
Flower类设计
创建一个花类:Flower类:
(1)string name、String color、 double price的私有成员
(2)包含有参构造方法和无参构造方法
(3)成员方法public void printInfo()
裁判测试程序样例中展示的是测试类的相关Java代码,其中缺失了部分代码,请补充完整,以保证测试程序正常运行。
裁判测试程序样例:
import java.util.Scanner;
/* 请在这里补充代码 */
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = in.next();
String color = in.next();
double price = in.nextDouble();
Flower flower1 = new Flower(name,color,price);
Flower flower2 = new Flower();
flower1.printInfo();
flower2.printInfo();
in.close();
}
}
输入样例:
百合花 白色 108.8
输出样例:
在这里给出相应的输出。例如:
百合花-白色-108.8
玫瑰花-红色-99.9
输入样例:
百合花 白色 108.8
输出样例:
在这里给出相应的输出。例如:
百合花-白色-108.8
玫瑰花-红色-99.9
题解:
class Flower{
private String name;
private String color;
private double price;
public Flower(){
this.name="玫瑰花";
this.color="红色";
this.price=99.9;
}
public Flower(String name,String color,double price){
this.name=name;
this.color=color;
this.price=price;
}
public void printInfo(){
System.out.println(this.name+'-'+this.color+'-'+this.price);
}
}
6-20 Person类
构造Person类。包括姓名(name),性别(sex)和年龄(age)。提供所有属性的set和get函数,提供print函数打印其信息
输入描述:
姓名(name),性别(sex)和年龄(age)
输出描述:
用户信息
裁判测试程序样例:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name = scan.next();
String sex = scan.next();
int age = scan.nextInt();
Person p = new Person();
p.setName(name);
p.setSex(sex);
p.setAge(age);
p.print();
scan.close();
}
}
/* 你的代码被嵌在这里 */
输入样例:
在这里给出一组输入。例如:
Lucy male 23
输出样例:
在这里给出相应的输出。例如:
name:Lucy; sex:male; age:23
题解
class Person{
private String name;
private String sex;
private int age;
public void setName(String name){
this.name=name;
}
public void setSex(String sex){
this.sex=sex;
}
public void setAge(int age){
this.age=age;
}
public String getName(){
return name;
}
public String getSex(){
return sex;
}
public int getAge(){
return age;
}
public void print(){
System.out.println("name:"+this.name+"; sex:"+this.sex+"; age:"+this.age);
}
}
6-21 设计一个长方体类Cuboid
要求:设计一个名为Cuboid的类表示长方体。这个类包括三个名为length、width和height 的double型数据域,它们分别表示长方体的长、宽和高。
一个无参构造方法, length、width、height的默认值都为1。 一个为length、width、height指定值的构造方法。
一个名为getArea()的方法返回这个长方体的表面积。 一个名为getVolume()的方法返回这个长方体的体积。
函数接口定义:
public double getArea(); public double getVolume();
裁判测试程序样例:
import java.util.Scanner;
/* 你的代码将被嵌入到这里 */
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double l = input.nextDouble();
double w = input.nextDouble();
double h = input.nextDouble();
Cuboid myCuboid = new Cuboid(l, w, h);
System.out.println(myCuboid.getArea());
System.out.println(myCuboid.getVolume());
input.close();
}
}
输入样例:
3.5 2 5
输出样例:
69.0
35.0
题解
class Cuboid{
private double l , w ,h;
public Cuboid(){
this.l=1;
this.w=1;
this.h=1;
}
public Cuboid(double l,double w,double h){
this.l=l;
this.w=w;
this.h=h;
}
public double getArea(){
return 2*(l*w+w*h+h*l);
}
public double getVolume(){
return l*w*h;
}
}
6-22 矩形
设计一个表示矩形的类Rectangle,这个类用一个表示坐标点的类Point的对象来表达它的左上角坐标,用一个表示尺寸的类Dimension的对象来表示它的大小。
你的程序要严格按照所给的类和函数的声明来实现。
函数接口定义:
/**
* Represents a point in 2D, with x and y, like (x,y).
*/
class Point {
private int x;
private int y;
/**
* Creates a point with coordinate at (x,y)
* @param x the x coordinate
* @param y the y coordinate
*/
public Point(int x, int y) {
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
* The generated string as: "(x,y)
*/
@Override
public String toString() {
}
/**
* Moves the point with dx and dy.
* @param dx the distance to be moved at x-axis
* @param dy the distance to be moved at y-axis
*/
public void move(int dx, int dy) {
}
/**
* Calculate the distance between this and p.
* @param p the other point.
* @return the distance between this and p.
*/
public double distance(Point p) {
}
}
/**
* A dimension in 2D, with width and height.
*/
class Dimension {
private int width;
private int height;
/**
* Creates a dimension with specified width and height.
* @param width the width of the dimension
* @param height the height of the dimension
*/
public Dimension(int width, int height) {
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
* The generated string as: "width by height"
*/
@Override
public String toString() {
}
/**
* Resizes the dimension with scales at width and height.
* Although the scales are in double, the result should be integers as well.
* @param widthScale the scale at width
* @param heightScale the scale at height
*/
public void resize(double widthScale, double heightScale) {
}
/**
* Calculate the area of this dimension.
* @return the area of this dimension.
*/
public int area() {
}
}
/**
* Represents a rectangle, with a point at its top-left and a dimension.
*
*/
class Rectangle {
private Point topleft;
private Dimension size;
/**
* Creates a rectangle.
* @param topleft the coordinate of its top-left
* @param size the dimension of its size
*/
public Rectangle(Point topleft, Dimension size) {
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
* The generated string as: "Rectangle at (x,y):width by height"
*/
public String toString() {
}
/**
* Moves the rectangle some distance.
* @param dx the distance to be moved at x-axis
* @param dy the distance to be moved at y-axis
*/
public void move(int dx, int dy) {
}
/**
* Resizes the rectangle at both width and height
* @param widthScale the scale at width
* @param heightScale the scale at height
*/
public void resize(double widthScale, double heightScale) {
}
/**
* Calculates the area of this rectangle.
* @return the area of this rectangle.
*/
public double area() {
}
/**
* Calculates the distance between this rectangle and r.
* @param r the other rectangle
* @return the distance between this rectangle and r.
*/
public double distance(Rectangle r) {
}
}
裁判测试程序样例:
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
int width = in.nextInt();
int height = in.nextInt();
Rectangle r = new Rectangle(
new Point(x,y), new Dimension(width, height));
Rectangle r2 = new Rectangle(
new Point(x,y), new Dimension(width, height));
int dx = in.nextInt();
int dy = in.nextInt();
r.move(dx, dy);
double widthScale = in.nextDouble();
double heightScale = in.nextDouble();
r.resize(widthScale, heightScale);
System.out.println(r);
System.out.printf("%.2f\n", r.area());
System.out.printf("%.2f\n", r.distance(r2));
in.close();
}
}
/* 请在这里填写答案 */
输入样例:
0 0 100 100 20 20 2 2
题解
/**
* Represents a point in 2D, with x and y, like (x,y).
*/
class Point {
private int x;
private int y;
/**
* Creates a point with coordinate at (x,y)
* @param x the x coordinate
* @param y the y coordinate
*/
public Point(int x, int y) {
this.x=x;
this.y=y;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
* The generated string as: "(x,y)
*/
@Override
public String toString() {
String point=String.format("Rectangle at (%d,%d):",x,y);
return point;
}
/**
* Moves the point with dx and dy.
* @param dx the distance to be moved at x-axis
* @param dy the distance to be moved at y-axis
*/
public void move(int dx, int dy) {
x=dx+x;
y=dy+y;
}
/**
* Calculate the distance between this and p.
* @param p the other point.
* @return the distance between this and p.
*/
public double distance(Point p) {
double number;
number=Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
return number;
}
}
/**
* A dimension in 2D, with width and height.
*/
class Dimension {
private int width;
private int height;
/**
* Creates a dimension with specified width and height.
* @param width the width of the dimension
* @param height the height of the dimension
*/
public Dimension(int width, int height) {
this.width=width;
this.height=height;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
* The generated string as: "width by height"
*/
@Override
public String toString() {
String dimention=String.format("%d by %d",width,height);
return dimention;
}
/**
* Resizes the dimension with scales at width and height.
* Although the scales are in double, the result should be integers as well.
* @param widthScale the scale at width
* @param heightScale the scale at height
*/
public void resize(double widthScale, double heightScale) {
width=(int)(width*widthScale);
height=(int)(height*heightScale);
}
/**
* Calculate the area of this dimension.
* @return the area of this dimension.
*/
public int area() {
int a;
a=width*height;
return a;
}
}
/**
* Represents a rectangle, with a point at its top-left and a dimension.
*
*/
class Rectangle {
private Point topleft;
private Dimension size;
/**
* Creates a rectangle.
* @param topleft the coordinate of its top-left
* @param size the dimension of its size
*/
public Rectangle(Point topleft, Dimension size) {
this.topleft=topleft;
this.size=size;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
* The generated string as: "Rectangle at (x,y):width by height"
*/
public String toString() {
return topleft.toString()+size.toString();
}
/**
* Moves the rectangle some distance.
* @param dx the distance to be moved at x-axis
* @param dy the distance to be moved at y-axis
*/
public void move(int dx, int dy) {
topleft.move(dx,dy);
}
/**
* Resizes the rectangle at both width and height
* @param widthScale the scale at width
* @param heightScale the scale at height
*/
public void resize(double widthScale, double heightScale) {
size.resize(widthScale, heightScale);
}
/**
* Calculates the area of this rectangle.
* @return the area of this rectangle.
*/
public double area() {
double number;
number=size.area();
return number;
}
/**
* Calculates the distance between this rectangle and r.
* @param r the other rectangle
* @return the distance between this rectangle and r.
*/
public double distance(Rectangle r) {
return topleft.distance(r.topleft);
}
}
6-23 设计矩形类Rectangle
设计一个名为Rectangle的类表示矩形。这个类包括: 两个名为width和height的int型数据域,它们分别表示矩形的宽和高。width和height的默认值都为10. 一个无参构造方法。 一个为width和height指定值的矩形构造方法。 一个名为getArea()的方法返回这个矩形的面积。 一个名为getPerimeter()的方法返回这个矩形的周长。。
裁判测试程序样例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int w = input.nextInt();
int h = input.nextInt();
Rectangle myRectangle1 = new Rectangle(w, h);
System.out.println(myRectangle1.getArea());
System.out.println(myRectangle1.getPerimeter());
Rectangle myRectangle2 = new Rectangle();
System.out.println(myRectangle2.getArea());
System.out.println(myRectangle2.getPerimeter());
input.close();
}
}
/* 请在这里填写答案 */
输入样例:
在这里给出一组输入。例如:
3 5
输出样例:
在这里给出相应的输出。例如:
15
16
100
40
题解
class Rectangle{
private int width;
private int height;
public Rectangle(){
this.width=10;
this.height=10;
}
public Rectangle(int width,int height){
this.width=width;
this.height=height;
}
public int getArea(){
return width*height;
}
public int getPerimeter(){
return 2*(width+height);
}
}
6-24 Animal接口
已知有如下Animal抽象类和IAbility接口,请编写Animal子类Dog类与Cat类,并分别实现IAbility接口,另外再编写一个模拟器类Simulator调用IAbility接口方法,具体要求如下。
已有的Animal抽象类定义:
abstract class Animal{
private String name; //名字
private int age; //年龄
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
已有的IAbility接口定义:
interface IAbility{
void showInfo(); //输出动物信息
void cry(); //动物发出叫声
}
需要你编写的Dog子类:
实现IAbility接口
showInfo方法输出Dog的name、age,输出格式样例为:我是一只狗,我的名字是Mike,今年2岁(注意:输出结果中没有空格,逗号为英文标点符号)
cry方法输出Dog 的叫声,输出格式样例为:旺旺
需要你编写的Cat子类:
实现IAbility接口
showInfo方法输出Cat的name、age,输出格式样例为:我是一只猫,我的名字是Anna,今年4岁(注意:输出结果中没有空格,逗号为英文标点符号)
cry方法输出Cat 的叫声,输出格式样例为:喵喵
需要你编写的模拟器类Simulator:
void playSound(IAbility animal):调用实现了IAbility接口类的showInfo和cry方法,并显示传入动物的名字和年龄
已有的Main类定义:
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
IAbility animal=null;
int type=input.nextInt();
String name=input.next();
int age=input.nextInt();
if (type==1)
animal=new Dog(name,age);
else
animal=new Cat(name,age);
Simulator sim=new Simulator();
sim.playSound(animal);
input.close();
}
}
/***请在这里填写你编写的Dog类、Cat类和Simulator类** */
输入样例:
(本题的评分点与输入样例无关)
第一个整数代表动物类型,1为狗类,2为猫类
1 Mike 2
输出样例:
我是一只狗,我的名字是Mike,今年2岁
旺旺
Mike
2
题解:
class Dog extends Animal implements IAbility {
public Dog(String name,int age){
super(name,age);
}
public void showInfo() {
System.out.println("我是一只狗,我的名字是" + getName() + ",今年" + getAge() + "岁");
}
public void cry() {
System.out.println("旺旺");
System.out.println(getName());
System.out.println(getAge());
}
}
class Cat extends Animal implements IAbility{
public Cat(String name,int age){
super(name,age);
}
public void showInfo() {
System.out.println("我是一只猫,我的名字是" + getName() + ",今年" + getAge() + "岁");
}
public void cry() {
System.out.println("喵喵");
System.out.println(getName());
System.out.println(getAge());
}
}
class Simulator {
public void playSound(IAbility animal) {
animal.showInfo();
animal.cry();
}
}
6-25 设计Student类
定义一个Student类,表示学生信息。Student类有学号(id,整型)、姓名(name,字符串)、性别(sex,字符型,m表示男性,f表示女性)三个私有数据域;有参构造方法将学号、姓名、性别设置为给定的参数;成员方法display显示学生的信息。
注意,Student类的定义应该这样开始:
class Student {
也就是说,Student类的class前面不要有public。
输入
输入学号、姓名、性别。
输出
输出学号、姓名、性别。
裁判测试程序样例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int id = in.nextInt();
String name = in.next();
char sex = in.next().charAt(0);
Student student = new Student(id, name, sex);
student.display();
in.close();
}
}
// 需要同学们完成部分,Student类
class Student {
// 数据成员
// 成员方法
}
输入样例:
1000
Tan
m
题解
class Student{
private int id;
private String name;
private char sex;
public Student(int id,String name ,char sex){
this.id=id;
this.name=name;
this.sex=sex;
}
public void display(){
System.out.println(this.id);
System.out.println(this.name);
System.out.println(this.sex);
}
}
6-26 jmu-Java-07多线程-Runnable与匿名类
在Main方法中启动一个线程t1
,该线程输出3行信息:
- 主线程名
- 线程t1的线程名
- 线程t1所实现的所有接口。提示:使用
System.out.println(Arrays.toString(getClass().getInterfaces()));
输出。
注:本题也可使用Lambda表达式实现。
裁判测试程序:
public class Main {
public static void main(String[] args) {
final String mainThreadName = Thread.currentThread().getName();
Thread t1 = /*这里放置你的代码*/
t1.start();
}
}
输入样例:
输出样例:
主线程名
线程t1的线程名
线程t1所实现的所有接口名
题解
new Thread(() -> {
System.out.println(mainThreadName);
System.out.println(Thread.currentThread().getName());
System.out.println(Arrays.toString(Thread.class.getInterfaces()));
});
6-27 ICompute接口
ICompute接口的实现
接口定义如下:
interface ICompute{
// 计算方法
int compute(int a, int b);
}
其中 a
和 b
为整型参数。
完善如下功能:
1.定义4个类:Plus、Subtract、Multiply、Divide,各自实现ICompute接口,完成两个数加减乘除运算。
2.注意除法运算中处理除数为0时返回-1
裁判测试程序样例:
import java.util.Scanner;
interface ICompute{
int compute(int a, int b);
}
/* 请在这里补充代码 */
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
Plus plus = new Plus();
System.out.println(a + "+" + b + "=" + plus.compute(a, b));
Subtract subtract = new Subtract();
System.out.println(a + "-" + b + "=" + subtract.compute(a, b));
Multiply multiply = new Multiply();
System.out.println(a + "*" + b + "=" + multiply.compute(a, b));
Divide divide = new Divide();
System.out.println(a + "/" + b + "=" + divide.compute(a, b));
in.close();
}
}
输入样例1:
3 0
输出样例1:
3+0=3
3-0=3
3*0=0
3/0=-1
输入样例2:
6 3
输出样例2:
6+3=9
6-3=3
6*3=18
6/3=2
题解:
class Plus implements ICompute {
public int compute(int a, int b) {
return a + b;
}
}
class Subtract implements ICompute {
public int compute(int a, int b) {
return a - b;
}
}
class Multiply implements ICompute {
public int compute(int a, int b) {
return a * b;
}
}
class Divide implements ICompute {
public int compute(int a, int b) {
if (b == 0) {
return -1;
} else {
return a / b;
}
}
}
6-28 Area接口与Perimeter接口
Area接口与Perimeter接口的实现
接口定义如下:
// 面积接口
interface Area {
double PI = 3.14;
double calArea();
}
// 周长接口
interface Perimeter {
double calPerimeter();
}
完善如下功能:
1.定义Circle类实现上述两个接口,包含半径成员变量和构造方法,其中成员变量为私有类型double radius。
2.定义Rectangle类实现上述两个接口,包含长、宽成员变量和构造方法,其中成员变量为私有类型double length、double width。
裁判测试程序样例:
import java.util.Scanner;
interface Area {
double PI = 3.14;
double calArea();
}
interface Perimeter {
double calPerimeter();
}
/* 请在这里补充代码 */
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double radius = in.nextDouble();
Circle c1 = new Circle(radius);
double length = in.nextDouble();
double width = in.nextDouble();
Rectangle r1 = new Rectangle(length, width);
System.out.println("c1's perimeter " + c1.calPerimeter());
System.out.println("c1's rea " + c1.calArea());
System.out.println("r1's perimeter " + r1.calPerimeter());
System.out.println("r1's rea " + r1.calArea());
in.close();
}
}
输入样例1:
4.0
3.0 4.0
输出样例1:
c1's perimeter 25.12
c1's rea 50.24
r1's perimeter 14.0
r1's rea 12.0
题解:
class Circle implements Area, Perimeter{
private double radius;
public Circle(double radius){
this.radius = radius;
}
public double calArea(){
return PI * radius * radius;
}
public double calPerimeter(){
return 2 * PI * radius;
}
}
class Rectangle implements Area, Perimeter{
private double length;
private double width;
public Rectangle(double length,double width){
this.length = length;
this.width = width;
}
public double calArea(){
return length * width;
}
public double calPerimeter(){
return 2 * (length + width);
}
}