沈师 Java程序设计 PTA 函数题答案

18 篇文章 91 订阅

1. 是否偶数 (10 分)

本题要求实现一个函数,判盘输入的整数是否是偶数,如果是偶数,返回true,否则返回false。
函数接口定义:

public static boolean isOdd(int data)

说明:其中 data 是用户传入的参数。 data 的值不超过int的范围。函数须返回 true 或者 false。
裁判测试程序样例:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int data=in.nextInt();
        System.out.println(isOdd(data));
    }
    
    /* 请在这里给出isOdd(i)函数 */
    
}

输入样例:
8
输出样例:
true
答案:

public static boolean isOdd(int data){
    return data%2==0?true:false;
}

2. 数组工具类的设计 (10 分)

本题要求设计一个名为MyArrays的类,根据调用的方式实现相应的方法。
函数接口定义:
请同学根据该类的调用方式和结果,自行设计MyArrays类中的方法,满足应用的需要。
裁判测试程序样例:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
    
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
    
        int array[]= new int[n];
    
        for(int i=0;i<n;i++)
        {
            array[i]=sc.nextInt();
        }
    
        MyArrays.printArray(array);//显示数组的内容
        MyArrays.sortArray(array);    //对数组元素排序
        MyArrays.printArray(array);//显示排序后的结果
        int sum=MyArrays.sumOfArray(array);//数组元素求和
        System.out.println(sum);//显示数组元素的和
    
    }

}

/* 请在这里填写MyArrays类的有关代码 */

输入样例:
5
5 4 6 8 3
输出样例:
5,4,6,8,3
3,4,5,6,8
26
答案:

class MyArrays {
    public static void printArray(int[] array){
        for(int i=0;i<array.length-1;i++)
            System.out.print(array[i]+",");
        System.out.println(array[array.length-1]);
    }

    public static void sortArray(int[] array){
        for(int i=0;i<array.length;i++){
            for(int j=i+1;j<array.length;j++){
                if(array[i]>array[j]){
                    int t=array[j];
                    array[j]=array[i];
                    array[i]=t;
                }
            }
        }
    }

    public static int sumOfArray(int[] array){
        int sum=0;
        for(int i=0;i<array.length;i++){
            sum+=array[i];
        }
        return sum;
    }
}

3. 根据派生类写出基类(Java) (5 分)

裁判测试程序样例中展示的是一段定义基类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 People() {
		
	}
	//有参
	public People(String id,String name) {
		this.id = id;
		this.name = name;
	}
	//setter & getter
	public void setId(String id) {
		this.id = id;
	}
	
	public String getId() {
		return this.id;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return this.name ;
	}
	
	public void say() {
		System.out.println("I'm a person! My name is " + this.name +".");
	}
	

4. 使用继承设计:教师类。 (5 分)

使用继承设计:教师类。 使程序运行结果为:
Li 40 信工院
教师的工作是教学。
函数接口定义:
定义类Teacher, 继承Person
裁判测试程序样例:

class Person{
    String name;
    int age;
    Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    void work(){

    }
    void show() {
        System.out.print(name+" "+age+" ");
    }
}

/* 请在这里填写答案 */

public class Main {

    public static void main(String[] args) {
    
         Teacher t = new Teacher("Li",40,"信工院");
         t.show();
         t.work();
    }
}

输入样例:
没有输入
输出样例:
Li 40 信工院
教师的工作是教学。
答案:

class Teacher extends Person{
    String professional;
    Teacher(String name, int age, String professional) {
        super(name, age);
        this.professional=professional;
    }
    @Override
    void work(){
        System.out.println(professional);
        System.out.println("教师的工作是教学。");
    }
}

5. jmu-Java-03面向对象基础-覆盖与toString (10 分)

Person类,Company类,Employee类。
其中Employee类继承自Person类,属性为:
private Company company;
private double salary;
现在要求编写Employee类的toString方法,格式为:父类的toString-company的toString-salary
函数接口定义:
public String toString()
输出样例
zhang-23-true-IBM-9000.123
答案:

public String toString() {
		return super.toString()+"-"+company.toString()+"-"+salary;
}

6. 重写父类方法equals (10 分)

在类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(Student stu) {
 return stu.id==this.id?true:false;
}

7. 从抽象类shape类扩展出一个圆形类Circle (10 分)

请从下列的抽象类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
{
	double radius;
	final static double PI = 3.1415926535;
	public Circle(double radius) {
		this.radius = radius;
	}
	@Override
	public double getArea() {
		// TODO Auto-generated method stub
		return PI*radius*radius;
	}
	@Override
	public double getPerimeter() {
		// TODO Auto-generated method stub
		return 2*PI*radius;
	}
	
}

8. 创建一个直角三角形类实现IShape接口 (10 分)

创建一个直角三角形类(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{
	double a,b;
	
	public RTriangle(double a, double b) {
		super();
		this.a = a;
		this.b = b;
	}
	public  double getArea() {
		return 0.5*a*b;
	}
	public double getPerimeter() {
		return a+b+Math.sqrt(a*a+b*b);
	}
}

9. jmu-Java-06异常-finally (10 分)

代码中向系统申请资源,到最后都要将资源释放。
现有一Resource类代表资源类,包含方法:

  1. open(String str)打开资源,声明为抛出Exception(包含出错信息)。
  2. close()方法释放资源,声明为抛出RuntimeException(包含出错信息)

现在根据open(String str)中str的不同,打印不同的信息。str的内容分为4种情况:

  1. fail fail,代表open和close均会出现异常。打印open的出错信息与close的出错信息。
  2. fail success,代表open抛出异常,打印open出错信息。close正常执行,打印resource release success
  3. success fail ,代表open正常执行,打印resource open success。close抛出异常,打印close出错信息。
  4. success success,代表open正常执行,打印resource open success,close正常执行打印resource release success

**注1:**你不用编写打印出错信息的代码。
**注2:**捕获异常后使用System.out.println(e)输出异常信息,e是所产生的异常。
裁判测试程序:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Resource resource = null;
    try{
        resource = new Resource();
        resource.open(sc.nextLine());
         /*这里放置你的答案*/

       sc.close();

}

以下输入样例代表输入success success。
输入样例
success success
输出样例
resource open success
resource release success
答案:

	System.out.println("resource open success");
}
catch(Exception e)
{ 
   	System.out.println(e);
}
try{
    	resource.close();
    	System.out.println("resource release success");
}
catch(RuntimeException e)
{
 	System.out.println(e);
}

10. jmu-Java-06异常-多种类型异常的捕获 (10 分)

如果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);
}

11. jmu-Java-07多线程-Thread (10 分)

编写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{
	int i;
	public MyThread(int i){
		this.i=i;
	}
	public void run () {
		for(int r=0;r<i;r++) {
			System.out.println(r);
		}
		System.out.println(Thread.currentThread().getName()+" "+isAlive());
	}
	
}

12. jmu-Java-07多线程-PrintTask (10 分)

编写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());
	}
}

共计12

进程已结束,退出代码0

  • 9
    点赞
  • 98
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

摘星喵Pro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值