Java第二部分题目集合(pta)

目录

7-1 jmu-Java-03面向对象基础-02-构造方法与初始化块

1.定义一个Person类

2.定义类的初始化块

3.编写静态初始化块

4.编写main方法

思考

输入样例:

输出样例:

实现代码: 

 7-2 日期类设计

输入格式:

输出格式:

输入样例1:

输出样例1:

输入样例2:

输出样例2:

输入样例3:

输出样例3:

输入样例4:

输出样例4:

实现代码: 

7-3 设计圆和圆柱体

输入格式:

输出格式:

输入样例:

输出样例:

 实现代码:

7-4 切分表达式——写个tokenizer吧

输入格式:

输出格式:

输入样例:

输出样例:

实现代码: 

7-5 使用公历类GregorianCalendar

输入格式:

输出格式:

输入样例:

输出样例:

实现代码: 

7-6 构造方法

输入格式:

输出格式:

输入样例:

输出样例:

实现代码:

7-7 Ring类设计

输入格式:

输出格式:

输入样例:

输出样例:

实现代码: 

7-8 求前N天 

输入格式:

输出格式:

输入样例1:

输出样例1:

输入样例2:

输出样例2:

实现代码: 

7-9 学生选课信息管理 

输入格式:

输出格式:

输入样例1:

输出样例1:

输入样例2:

输出样例2:

输入样例3:

输出样例3:

输入样例4:

输出样例4:

实现代码: 

 

 

 

 


7-1 jmu-Java-03面向对象基础-02-构造方法与初始化块

1.定义一个Person类

属性:String nameboolean genderint ageint id ,所有的变量必须为私有(private)。
无参构造函数:Person()功能:打印This is constructor 。
有参构造函数:Person(name, gender, age) 功能:给属性赋值。
建议:使用Eclipse自动生成toString方法

2.定义类的初始化块

为Person类加入初始化块,在初始化块中对id属性赋值,并且要保证每次的值比上次创建的对象的值+1。然后在下一行打印This is initialization block, id is ... 其中...是id的值。
提示:可为Person类定义一个static属性来记录所创建的对象个数。

3.编写静态初始化块

打印This is static initialization block

4.编写main方法

  • 首先输入n,代表要创建的对象数量。
  • 然后从控制台分别读取n行的name age gender, 并调用有参构造函数Person(name, age, gender)新建对象 。
  • 将创建好的n个对象逆序输出(即输出toString()方法)。
  • 使用无参构造函数新建一个Person对象,然后直接打印该对象。

思考

初始化类与对象有几种方法,构造函数、初始化块、静态初始化块。这三种方法执行的先后顺序是什么?各执行几次。

输入样例:

3
a 11 false
b 12 true
c 10 false

输出样例:

This is static initialization block
This is initialization block, id is 0
This is initialization block, id is 1
This is initialization block, id is 2
Person [name=c, age=10, gender=false, id=2]
Person [name=b, age=12, gender=true, id=1]
Person [name=a, age=11, gender=false, id=0]
This is initialization block, id is 3
This is constructor
null,0,false,3
Person [name=null, age=0, gender=false, id=3]

实现代码: 

import java.util.Scanner;
class Person{
    private String name;
    private boolean gender;
    private int age;
    private int id;
    private static int sum=0;
    Person(){
        System.out.println("This is constructor");
        System.out.println(this.name+","+this.age+","+this.gender+","+this.id);
    }
    Person(String name,int age,boolean gender){
        this.name=name;
        this.age=age;
        this.gender=gender;
    }
    {
        this.id=sum++;
        System.out.println("This is initialization block, id is "+this.id);
    }
    static{
        System.out.println("This is static initialization block");
    }
   public  String toString(){
        return "Person [name="+this.name+", age="+this.age+", gender="+this.gender+", id="+this.id+"]";
    }
}
public class Main{
public static void main(String[] args){
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    Person sb[]=new Person[n];
    for(int i=0;i<n;i++){
        Person person=new Person(sc.next(),sc.nextInt(),sc.nextBoolean());
        sb[i]=person;
    }
    for(int i=n-1;i>=0;i--){
        System.out.println(sb[i].toString());
    }
    Person SB=new Person();
    System.out.println(SB.toString());
}
}

 7-2 日期类设计

参考题目3和日期相关的程序,设计一个类DateUtil,该类有三个私有属性year、month、day(均为整型数),其中,year∈[1820,2020] ,month∈[1,12] ,day∈[1,31] , 除了创建该类的构造方法、属性的getter及setter方法外,需要编写如下方法:

public boolean checkInputValidity();//检测输入的年、月、日是否合法
public boolean isLeapYear(int year);//判断year是否为闰年
public DateUtil getNextNDays(int n);//取得year-month-day的下n天日期
public DateUtil getPreviousNDays(int n);//取得year-month-day的前n天日期
public boolean compareDates(DateUtil date);//比较当前日期与date的大小(先后)
public boolean equalTwoDates(DateUtil date);//判断两个日期是否相等
public int getDaysofDates(DateUtil date);//求当前日期与date之间相差的天数
public String showDate();//以“year-month-day”格式返回日期值

应用程序共测试三个功能:

  1. 求下n天
  2. 求前n天
  3. 求两个日期相差的天数

注意:严禁使用Java中提供的任何与日期相关的类与方法,并提交完整源码,包括主类及方法(已提供,不需修改)

程序主方法如下:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int year = 0;
        int month = 0;
        int day = 0;

        int choice = input.nextInt();

        if (choice == 1) { // test getNextNDays method
            int m = 0;
            year = Integer.parseInt(input.next());
            month = Integer.parseInt(input.next());
            day = Integer.parseInt(input.next());

            DateUtil date = new DateUtil(year, month, day);

            if (!date.checkInputValidity()) {
                System.out.println("Wrong Format");
                System.exit(0);
            }

            m = input.nextInt();

            if (m < 0) {
                System.out.println("Wrong Format");
                System.exit(0);
            }

            System.out.print(date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " next " + m + " days is:");
            System.out.println(date.getNextNDays(m).showDate());
        } else if (choice == 2) { // test getPreviousNDays method
            int n = 0;
            year = Integer.parseInt(input.next());
            month = Integer.parseInt(input.next());
            day = Integer.parseInt(input.next());

            DateUtil date = new DateUtil(year, month, day);

            if (!date.checkInputValidity()) {
                System.out.println("Wrong Format");
                System.exit(0);
            }

            n = input.nextInt();

            if (n < 0) {
                System.out.println("Wrong Format");
                System.exit(0);
            }

            System.out.print(
                    date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " previous " + n + " days is:");
            System.out.println(date.getPreviousNDays(n).showDate());
        } else if (choice == 3) {    //test getDaysofDates method
            year = Integer.parseInt(input.next());
            month = Integer.parseInt(input.next());
            day = Integer.parseInt(input.next());

            int anotherYear = Integer.parseInt(input.next());
            int anotherMonth = Integer.parseInt(input.next());
            int anotherDay = Integer.parseInt(input.next());

            DateUtil fromDate = new DateUtil(year, month, day);
            DateUtil toDate = new DateUtil(anotherYear, anotherMonth, anotherDay);

            if (fromDate.checkInputValidity() && toDate.checkInputValidity()) {
                System.out.println("The days between " + fromDate.showDate() + 
                        " and " + toDate.showDate() + " are:"
                        + fromDate.getDaysofDates(toDate));
            } else {
                System.out.println("Wrong Format");
                System.exit(0);
            }
        }
        else{
            System.out.println("Wrong Format");
            System.exit(0);
        }        
    }
}

输入格式:

有三种输入方式(以输入的第一个数字划分[1,3]):

  • 1 year month day n //测试输入日期的下n天
  • 2 year month day n //测试输入日期的前n天
  • 3 year1 month1 day1 year2 month2 day2 //测试两个日期之间相差的天数

输出格式:

  • 当输入有误时,输出格式如下:
    Wrong Format
  • 当第一个数字为1且输入均有效,输出格式如下:
    year1-month1-day1 next n days is:year2-month2-day2
    
  • 当第一个数字为2且输入均有效,输出格式如下:
    year1-month1-day1 previous n days is:year2-month2-day2
    
  • 当第一个数字为3且输入均有效,输出格式如下:
    The days between year1-month1-day1 and year2-month2-day2 are:值
    

输入样例1:

在这里给出一组输入。例如:

3 2014 2 14 2020 6 14

输出样例1:

在这里给出相应的输出。例如:

The days between 2014-2-14 and 2020-6-14 are:2312

输入样例2:

在这里给出一组输入。例如:

2 1834 2 17 7821

输出样例2:

在这里给出相应的输出。例如:

1834-2-17 previous 7821 days is:1812-9-19

输入样例3:

在这里给出一组输入。例如:

1 1999 3 28 6543

输出样例3:

在这里给出相应的输出。例如:

1999-3-28 next 6543 days is:2017-2-24

输入样例4:

在这里给出一组输入。例如:

0 2000 5 12 30

输出样例4:

在这里给出相应的输出。例如:

Wrong Format

实现代码: 

import java.util.Scanner;
class DateUtil{
    private int year;
    private int month;
    private int day;
    int a[]=new int[17];
    DateUtil(DateUtil d){//构造方法(用来后面比较)
        this.day=d.getDay();
        this.month=d.getMonth();
        this.year=d.getYear();
        a[1]=31;a[2]=28;a[3]=31;a[4]=30;a[5]=31;a[6]=30;
        a[7]=31;a[8]=31;a[9]=30;a[10]=31;a[11]=30;a[12]=31;
    }//完成
    DateUtil(int year,int month,int day){//构造方法
        this.year=year;
        this.month=month;
        this.day=day;
        a[1]=31;a[2]=28;a[3]=31;a[4]=30;a[5]=31;a[6]=30;
        a[7]=31;a[8]=31;a[9]=30;a[10]=31;a[11]=30;a[12]=31;
    }
    public void setDay(int day){
        this.day=day;
    }
    public int getDay(){
        return this.day;
    }
    public void setMonth(int month){
        this.month=month;
    }
    public int getMonth(){
        return this.month;
    }
    public void setYear(int year){
        this.year=year;
    }
    public int getYear(){
        return this.year;
    }
    public boolean checkInputValidity(){//检测合不合理
        if(this.year<1820||this.year>2020)
            return false;
        if(this.month<1||this.month>12)
            return false;
        if(this.isLeapYear(this.year)==true){
            if(this.month==2){
                if(this.day<1||this.day>29)
                    return false;
            }
            else{
                if(this.day<1||day>a[this.month])
                    return false;
            }
        }
        else{
            if(this.day<1||this.day>a[this.month])
                return false;
        }
           return true;
    }
    public boolean isLeapYear(int year){//判断是不是闰年
        if(year%400==0||year%4==0&&year%100!=0)
            return true;
        return false;
    }
    public DateUtil getNextNDays(int n){//下n天日期
        while(n>365){
            if(this.isLeapYear(this.year)&&this.month<=2){
                if(this.month==2&&this.day==29){
                    this.day=1;
                    this.month=3;
                }
                this.year++;
                n=n-366;
            }
            else if(this.isLeapYear(this.year+1)&&this.month>2){
                this.year++;
                n=n-366;
            }
            else{
                this.year++;
                n=n-365;
            }
        }
        for(int i=0;i<n;i++){
            this.day++;
            if(this.isLeapYear(this.year)&&this.month==2){
                if(this.day>29){
                    this.month++;
                    this.day=1;
                }
            }
            else if(this.day>a[this.month]){
                this.month++;
                this.day=1;
                if(this.month>12){
                    this.month=1;
                    this.year++;
                }
            }
        }
        return this;
    }
    public DateUtil getPreviousNDays(int n){//前n天
        while(n>365){
            if(this.isLeapYear(this.year)&&this.month>2){
                n=n-366;
                this.year=this.year-1;
            }
            else if(this.isLeapYear(this.year-1)&&this.month<=2){
                n=n-366;
                this.year--;
            }
            else{
                n=n-365;
                this.year--;
            }
        }
        for(int i=0;i<n;i++){
            this.day--;
            if(this.day<=0){
                this.month--;
                if(this.month<=0){
                    this.month=12;
                    this.year--;
                }
                if(this.isLeapYear(this.year)&&this.month==2){
                    this.day=29;
                }
                else{
                    this.day=a[this.month];
                }
            }
        }
        return this;
    }
    public boolean compareDates(DateUtil date){//比较大小
        if(this.year>date.getYear())
            return true;
        else if(this.year==date.getYear()&&this.month>date.getMonth())
            return true;
        else if(this.year==date.getYear()&&this.month==date.getMonth()&&this.day>date.getDay())
            return true;
        return false;
    }
    public boolean equalTwoDates(DateUtil date){
        if(this.year==date.getYear()&&this.month==date.getMonth()&&this.day==date.getDay())
            return true;
        return false;
    }
    public int getDaysofDates(DateUtil date){//相差几天
        int res=0;
        boolean b=this.compareDates(date);
        if(b){//this比date大,所以this减,一直减到跟date一样
            while(this.year-date.getYear()>=2){
                if(this.isLeapYear(this.year)&&this.month>2){
                    res=res+366;
                }
                else if(this.isLeapYear(this.year-1)&&this.month<=2){
                    res=res+366;
                }
                else
                    res=res+365;
                this.year--;
            }
            while(true){
                if(this.equalTwoDates(date))
                    break;
                res++;
                this.day--;
                if(this.day==0){
                    this.month--;
                    if(this.month==0){
                        this.month=12;
                        this.year--;
                    }
                    if(this.isLeapYear(this.year)&&this.month==2)
                        this.day=29;
                    else
                        this.day=a[this.month];
                }
            }
        }
        else{//这个时候加就完事儿了,方法跟上面差不多
            while(date.getYear()-this.year>=2){
                if(this.isLeapYear(this.year)&&this.month<=2)
                    res=res+366;
                else if(this.isLeapYear(this.year+1)&&this.month>2){
                    res=res+366;
                }
                else 
                    res=res+365;
                this.year++;
            }
            while(true){
                if(this.equalTwoDates(date))
                    break;
                res++;
                this.day++;
                if(this.isLeapYear(this.year)&&this.month==2){
                    if(this.day>29){
                        this.month++;
                        this.day=1;
                    }
                }
                else if(this.day>a[this.month]){
                    this.month++;
                    this.day=1;
                    if(this.month>12){
                        this.month=1;
                        this.year++;
                    }
                }
            }
        }
        return res;
    }
    public String showDate(){
        return this.year+"-"+this.month+"-"+this.day;
    }
}


public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int year = 0;
        int month = 0;
        int day = 0;

        int choice = input.nextInt();

        if (choice == 1) { // test getNextNDays method
            int m = 0;
            year = Integer.parseInt(input.next());
            month = Integer.parseInt(input.next());
            day = Integer.parseInt(input.next());

            DateUtil date = new DateUtil(year, month, day);

            if (!date.checkInputValidity()) {
                System.out.println("Wrong Format");
                System.exit(0);
            }

            m = input.nextInt();

            if (m < 0) {
                System.out.println("Wrong Format");
                System.exit(0);
            }

            System.out.print(date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " next " + m + " days is:");
            System.out.println(date.getNextNDays(m).showDate());
        } else if (choice == 2) { // test getPreviousNDays method
            int n = 0;
            year = Integer.parseInt(input.next());
            month = Integer.parseInt(input.next());
            day = Integer.parseInt(input.next());

            DateUtil date = new DateUtil(year, month, day);

            if (!date.checkInputValidity()) {
                System.out.println("Wrong Format");
                System.exit(0);
            }

            n = input.nextInt();

            if (n < 0) {
                System.out.println("Wrong Format");
                System.exit(0);
            }

            System.out.print(
                    date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " previous " + n + " days is:");
            System.out.println(date.getPreviousNDays(n).showDate());
        } else if (choice == 3) {    //test getDaysofDates method
            year = Integer.parseInt(input.next());
            month = Integer.parseInt(input.next());
            day = Integer.parseInt(input.next());

            int anotherYear = Integer.parseInt(input.next());
            int anotherMonth = Integer.parseInt(input.next());
            int anotherDay = Integer.parseInt(input.next());

            DateUtil fromDate = new DateUtil(year, month, day);
            DateUtil toDate = new DateUtil(anotherYear, anotherMonth, anotherDay);

            if (fromDate.checkInputValidity() && toDate.checkInputValidity()) {
                System.out.println("The days between " + fromDate.showDate() + 
                        " and " + toDate.showDate() + " are:"
                        + fromDate.getDaysofDates(toDate));
            } else {
                System.out.println("Wrong Format");
                System.exit(0);
            }
        }
        else{
            System.out.println("Wrong Format");
            System.exit(0);
        }        
    }
}

7-3 设计圆和圆柱体

编写一个完整的Java Application 程序。包含类Circle、Cylinder、Main,具体要求如下。

(1)编写类Circle,表示圆形对象,包含以下成员
①属性:
1)  radius:私有,double型,圆形半径;
②方法:
1)  Circle(double radius), 构造方法,用参数设置圆的半径
2)  Circle(),构造方法,将圆形初始化为半径为0。
3)  void setRadius(double r):用参数r设置radius的值
4)  double getRadius():返回radius的值
5)  double getArea(),返回圆形的面积
6)  double getPerimeter(),返回圆形的周长
7)  public String toString( ),将把当前圆对象的转换成字符串形式,例如圆半径为10.0,返回字符串"Circle(r:10.0)"。
(2)编写一个类Cylinder,表示圆柱形对象,包含以下成员
①属性:
1)  height:私有,double型,圆柱体高度;
2)  circle:私有,Circle类型,圆柱体底面的圆形;
②方法:
1)  Cylinder(double height,Circle circle), 构造方法,用参数设置圆柱体的高度和底面的圆形
2)  Cylinder(),构造方法,将圆柱体的高度初始化为0,底面圆形初始化为一个半径为0的圆形。
3)  void setHeight(double height):用参数height设置圆柱体的高度
4)  double getHeight():返回圆柱体的高度
5)  void setCircle(Circle circle):用参数circle设置圆柱体底面的圆形
6)  Circle getCircle():返回圆柱体底面的圆形
7)  double getArea(),重写Circle类中的area方法,返回圆柱体的表面积
8)  double getVolume(),返回圆柱体的体积
9)  public String toString( ),将把当前圆柱体对象的转换成字符串形式,例如半径为10.0,高为5.0,返回字符串"Cylinder(h:5.0,Circle(r:10.0))"。
(3)编写公共类Main,在main()方法中实现如下功能
输入一个整数n,表示有n个几何图形。
对于每一个几何图形,先输入一个字符串,“Circle”表示圆形,“Cylinder”表示圆柱体。
如果是圆形,输入一个浮点数表示其半径。要求计算其面积和周长并输出。
如果是圆柱体,输入两个浮点数分别表示其半径和高度。要求计算其面积和体积并输出。

将以下代码附在自己的代码后面:

public class Main{
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        for(int i = 0; i < n; i++) {
            String str = input.next();
            if(str.equals("Circle")) {
                Circle c = new Circle(input.nextDouble());
                System.out.println("The area of " + c.toString() + " is " + String.format("%.2f",c.getArea()));
                System.out.println("The perimeterof " + c.toString() + " is "+ String.format("%.2f",c.getPerimeter()));
            } else if(str.equals("Cylinder")) {
                Cylinder r = new Cylinder(input.nextDouble(), new Circle(input.nextDouble()));
                System.out.println("The area of " + r.toString() + " is " + String.format("%.2f",r.getArea()));
                System.out.println("The volume of " + r.toString() + " is " + String.format("%.2f",r.getVolume()));
            }
        }
    }
}

输入格式:

第一行输入一个整数n,表示有n个几何图形。
以下有n行,每行输入一个几何图形的数据。
每行先输入一个字符串表示几何图形的类型,“Circle”表示圆形,“Cylinder”表示圆柱体。
如果是圆形,输入一个浮点数表示其半径。
如果是圆柱体,输入两个浮点数分别表示其半径和高度。

输出格式:

如果是圆形,要求计算其面积和周长并输出。
如果是圆柱体,要求计算其面积和体积并输出。
注意,圆周率用Math.PI

输入样例:

在这里给出一组输入。例如:

4
Circle 10.0
Cylinder 10.0 10.0
Circle 1.1
Cylinder 1.1 3.4

输出样例:

在这里给出相应的输出。例如:

The area of Circle(r:10.0) is 314.16
The perimeterof Circle(r:10.0) is 62.83
The area of Cylinder(h:10.0,Circle(r:10.0)) is 1256.64
The volume of Cylinder(h:10.0,Circle(r:10.0)) is 3141.59
The area of Circle(r:1.1) is 3.80
The perimeterof Circle(r:1.1) is 6.91
The area of Cylinder(h:1.1,Circle(r:3.4)) is 96.13
The volume of Cylinder(h:1.1,Circle(r:3.4)) is 39.95

 实现代码:

import java.util.Scanner;
import java.lang.Math;
public class Main{
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        for(int i = 0; i < n; i++) {
            String str = input.next();
            if(str.equals("Circle")) {
                Circle c = new Circle(input.nextDouble());
                System.out.println("The area of " + c.toString() + " is " + String.format("%.2f",c.getArea()));
                System.out.println("The perimeterof " + c.toString() + " is "+ String.format("%.2f",c.getPerimeter()));
            } else if(str.equals("Cylinder")) {
                Cylinder r = new Cylinder(input.nextDouble(), new Circle(input.nextDouble()));
                System.out.println("The area of " + r.toString() + " is " + String.format("%.2f",r.getArea()));
                System.out.println("The volume of " + r.toString() + " is " + String.format("%.2f",r.getVolume()));
            }
        }
    }
}

class Circle{
    private double radius;

    public Circle(double radius){
        this.radius = radius;
    }
    public Circle(){
        radius = 0;
    }
    public void setRadius(double r){
        radius = r;
    }
    public double getRadius(){
        return this.radius;
    }
    public double getArea(){
        return Math.PI * Math.pow(radius,2);
    }
    public double getPerimeter(){
        return 2 * Math.PI * radius;
    }
    @Override
    public String toString(){
        return "Circle(r:" + radius + ")";
    }
}

class Cylinder{
    private double height;
    private Circle circle;

    public Cylinder(double height, Circle circle){
        this.height = height;
        this.circle = circle;
    }
    public Cylinder(){
        height = 0;
        circle = new Circle(0);
    }
    public void setHeight(double height){
        this.height = height;
    }
    public double getHeight(){
        return height;
    }
    public void setCircle(Circle circle){
        this.circle = circle;
    }
    public Circle getCircle(){
        return circle;
    }
    public double getArea(){
        return 2 * Math.PI * circle.getRadius() * circle.getRadius() + 2 * Math.PI * circle.getRadius() * height;
    }
    public double getVolume(){
        return Math.PI * circle.getRadius() * circle.getRadius() * height;
    }
    @Override
    public String toString(){
        return "Cylinder(h:" + height + "," + circle.toString() + ")";
    }
}

7-4 切分表达式——写个tokenizer吧

[先说点出题背景]

这个题是为低年级同学、学C语言的同学准备的,因为,对这部分同学,这个题目编写起来略有一点复杂。如果是高年级、学过了正则表达式(Regular Expression)的同学或者学过了Java等OO语言的同学做这个题,应当发现这题比较简单吧。哦,对了,什么是tokenizer?请自行查询解决。反正在此处不应翻译成“令牌解析器”。

[正题]

四则运算表达式由运算数(必定包含数字,可能包含正或负符号小数点)、运算符(包括+-*/)以及小括号(())组成,每个运算数、运算符和括号都是一个token(标记)。现在,对于给定的一个四则运算表达式,请把她的每个token切分出来。题目保证给定的表达式是正确的,不需要做有效性检查。

输入格式:

在一行中给出长度不超过40个字符的表达式,其中没有空格,仅由上文中token的字符组成

输出格式:

依次输出表达式中的tokens,每个token占一行。

输入样例:

32*((2-2)+5)/(-15)

输出样例:

32
*
(
(
2
-
2
)
+
5
)
/
(
-15
)

实现代码: 

import java.util.Scanner;
public class Main{
     public static void main(String[] args){
	        Scanner sc=new Scanner(System.in);
	        String s=sc.next();
	        char ch[]=s.toCharArray();
	        for(int i=0;i<s.length();i++){
	            System.out.print(ch[i]);
	            if(i+1==s.length())
	                System.out.printf("\n");
	            else if(ch[i]>='0'&&ch[i]<='9'&&!(ch[i+1]>='0'&&ch[i+1]<='9')&&ch[i+1]!='.')
	                System.out.printf("\n");
	            else if(ch[i]=='*'||ch[i]=='/'||ch[i]=='('||ch[i]==')')
	                System.out.printf("\n");
	            else if((ch[i]=='+'||ch[i]=='-')&&i-1!=-1){
	                if(ch[i-1]==')'||ch[i-1]>='0'&&ch[i-1]<='9')
	                    System.out.printf("\n");
	            }
	        }
	    }
}

7-5 使用公历类GregorianCalendar

使用公历类 GregorianCalendar,公历类 GregorianCalendar有方法setTimeInMillis(long);可以用它来设置从1970年1月1日算起的一个特定时间。请编程从键盘输入一个长整型的值,然后输出对应的年、月和日。例如输入:1234567898765,输出:2009-1-14

输入格式:

输入

1234567898765 (毫秒数)

输出格式:

输出

2009-1-14 (输出年、月和日,实际应该是2月,因为Java API 从0开始计算月份)

输入样例:

1450921070108

输出样例:

2015-11-24

实现代码: 

import java.util.*;
public class Main {
	    public static void main(String[]args){
	        Scanner in=new Scanner(System.in);
	        GregorianCalendar g=new GregorianCalendar();
	        g.setTimeInMillis(in.nextLong());
	        System.out.println(g.get(Calendar.YEAR)+"-"+g.get(Calendar.MONTH)+"-"+g.get(Calendar.DAY_OF_MONTH));
	    }
	}

7-6 构造方法

请补充以下代码,完成输出要求。

public class Main { public Main(){ System.out.println("构造方法一被调用了"); }
public Main(int x){ this(); System.out.println("构造方法二被调用了"); }
public Main(boolean b){ this(1); System.out.println("构造方法三被调用了"); }
public static void main(String[] args) { } } 

输入格式:

输出格式:

输出以下三行:
构造方法一被调用了
构造方法二被调用了
构造方法三被调用了

输入样例:

输出样例:

构造方法一被调用了
构造方法二被调用了
构造方法三被调用了

实现代码:

public class Main {
    public Main(){
        System.out.println("构造方法一被调用了");
    }
    public Main(int x){
        this();
        System.out.println("构造方法二被调用了");
    }
    public Main(boolean b){
        this(1);
        System.out.println("构造方法三被调用了");
    }
    public static void main(String[] args) {
         Main a = new Main(true);
    }
}

7-7 Ring类设计

编写一个圆环类Ring的Java程序。

a定义圆环类的2个数据成员,分别是内半径innerRadius,外半径outerRadius,这些属性通过get和set方法进行封装。

b 定义圆环类有参构造方法Ring(int innerRadius,int outerRadius),在有参构造方法中加入System.out.println("constructor");

c完成无参构造方法Ring(),要求在无参构造方法中使用this调用有参构造方法给两个半径赋值(外半径赋值3,内半径赋值1)

d 圆环类中定义 public int getArea()方法可以返回其面积。面积求出后强制转换为整型值返回,π使用Math.PI表示。


在Main类中先生成一个圆环类对象,这个圆环的两个半径通过键盘读入,调用求面积方法求出面积后,输出面积。

然后再次定义一个圆环对象,调用无参构造方法,调用求面积方法求出面积后,输出面积。

输入格式:

输入在一行中先给出内半径,再给出外半径。

输出格式:

在一行中输出圆环的面积。

输入样例:

在这里给出一组输入。先是内半径,然后是外半径,例如:

1   2

输出样例:

在这里给出相应的输出。例如:

constructor
9
constructor
25

实现代码: 

import java.util.*;
import java.lang.Math;
class Ring{
    private int innerRadius;
    private int outerRadius;
    private double s;
    public void set1(int a){
        this.innerRadius=a;
    }
    public int get1(){
        return this.innerRadius;
    }
    public void set2(int a){
        this.outerRadius=a;
    }
    public int get2(){
        return this.outerRadius;
    }
    Ring(int innerRadius,int outerRadius){
        System.out.println("constructor");
        this.set1(innerRadius);
        this.set2(outerRadius);
    }
    Ring(){
        this(1,3);
    }
    public void qius(){
        this.s=Math.PI*this.outerRadius*this.outerRadius-Math.PI*this.innerRadius*this.innerRadius;
    }
    public  void getArea(){
       System.out.println((int)this.s);
    }
}

public class Main {
	 public static void main(String[] args){
	        Scanner sc=new Scanner(System.in);
	        Ring r1=new Ring(sc.nextInt(),sc.nextInt());
	        r1.qius();
	        r1.getArea();
	        Ring r2=new Ring();
	        r2.qius();
	        r2.getArea();
}
}

7-8 求前N天 

输入年月日的值(均为整型数),同时输入一个取值范围在[-10,10] 之间的整型数n,输出该日期的前n天(当n > 0时)、该日期的后n天(当n<0时)。
其中年份取值范围为 [1820,2020] ,月份取值范围为[1,12] ,日期取值范围为[1,31] 。
注意:不允许使用Java中任何与日期有关的类或方法。

输入格式:

在一行中输入年月日的值以及n的值,可以用一个或多个空格或回车分隔。

输出格式:

  1. 当输入的年、月、日以及n的值非法时,输出“Wrong Format”;
  2. 当输入数据合法时,输出“n days ago is:年-月-日”

输入样例1:

在这里给出一组输入。例如:

2018  6 19 8 

输出样例1:

在这里给出相应的输出。例如:

8 days ago is:2018-6-11

输入样例2:

在这里给出一组输入。例如:

2018  6 19 -8 

输出样例2:

在这里给出相应的输出。例如:

-8 days ago is:2018-6-27

实现代码: 

import java.util.*;
public class Main {
	     //主函数
	     public static void main(String[] args) {
	         Scanner sc = new Scanner(System.in);
	         int year = sc.nextInt();
	         int month = sc.nextInt();
	         int day = sc.nextInt();
	         int n=sc.nextInt();
	         nextDate(year,month,day,n);
	     }
	     //判断year是否为闰年,返回boolean类型
	    public static boolean isLeapYear(int year) {
	        if((year % 4 == 0 && year % 100 !=0 )||year % 400 == 0)
	        return true;
	        return false;
	    }
	     //判断输入日期是否合法,返回布尔值
	    public static boolean checkInputValidity(int year,int month,int day,int n) {
	        int a[]=new int[13];
	        a[1]=31;a[2]=29;a[3]=31;a[4]=30;a[5]=31;a[6]=30;a[7]=31;a[8]=31;a[9]=30;a[10]=31;a[11]=30;a[12]=31;
	        if(!isLeapYear(year)) {
	            a[2] = 28;
	        }
	       if(year>=1820&&year<=2020&&month>0&&month<=12&&day<=a[month]&&day>0&&n<=10&&n>=-10) {
	    	   return true;
	       }
	        return false;
	    }
	     //求输入日期的前n天
	    public static void nextDate(int year,int month,int day,int n) {
	        int[] a=new int[]{0,31,29,31,30,31,30,31,31,30,31,30,31};
	        int d=0,m=0,b;
	        if(!isLeapYear(year))//如果不是闰年
	            a[2] = 28;
	        if(checkInputValidity(year,month,day,n)) {//如果输入的数字合法
	            if(n>0){//如果是算前几天
	                if(month!=1) {//如果不是1月
	                    if(n<day) {//如果几号大于前几天
	                        m=month;
	                        d=day-n;
	                    }
	                    else  {//如果几号小于前几天
	                        b=n-day;
	                        m=month-1;
	                        d=a[month-1]-b;
	                    }
	                }
	                else {//如果是1月
	                    if(n<day) {//如果几号大于前几天
	                        m=month;
	                        d=day-n;
	                    }
	                    else  {//如果几号小于前几天
	                        b=n-day;
	                        year=year-1;
	                        m=12;
	                        d=31-b;
	                    }
	                }
	                System.out.println(n+" days ago is:"+year+"-"+m+"-"+d);
	            }
	            else{//如果是算后几天
	                n=-n;
	                if(month!=12) {//如果不是12月
	                    if(n+day<a[month]) {//如果几天后小于该月天数
	                        m=month;
	                        d=day+n;
	                    }
	                    else {//如果几天后大于该月天数
	                        b=n+day;
	                        m=month+1;
	                        d=b-a[month];
	                    }
	                }
	                else {//如果是12月
	                    if(n+day<a[month]) {//如果几天后小于该月天数
	                        m=month;
	                        d=day+n;
	                    }
	                    else  {//如果几天后大于该月天数
	                        b=n+day;
	                        year=year+1;
	                        m=1;
	                        d=b-a[month];
	                    }
	                }
	                n=-n;
	                System.out.println(n+" days ago is:"+year+"-"+m+"-"+d);
	            }
	        }
	        else//如果输入的数字非法
	            System.out.println("Wrong Format");
	    }
	}

7-9 学生选课信息管理 

设计一个学生选课信息管理系统,从屏幕读入学生、课程信息,执行学生选课操作,并显示选课结果。要求如下:

(1)设计一个学生类Student,包括:

学号stuID、姓名stuName、学生对象的数量stuNum三个数据域;
一个无参构造方法,创建默认的学生,构造方法中输出“学生类无参构造方法”;
一个有参构造方法,创建指定学号stuID、姓名stuName的学生,构造方法中输出“学生类有参构造方法”;
所有数据域的访问器方法;
两个修改器方法,可以修改学号stuID、姓名stuName的值。

(2)设计一个课程类Course,包括:

课程编号cID、课程名cName、课程对象的数量cNum三个数据域;
一个无参构造方法,创建默认的课程,构造方法中输出“课程类无参构造方法”;
一个有参构造方法,创建指定课程编号cID、课程名cName的课程,构造方法中输出“课程类有参构造方法”;
所有数据域的访问器方法;
两个修改器方法,可以修改课程编号cID、课程名cName的值。

(3)设计一个学生选课类Schedule,包括:

学生列表stuList、课程列表cList、学生选课总数schNum三个数据域,两个列表的默认长度任意设定;
一个无参构造方法,创建默认的学生选课对象;
一个学生选课方法 addCourse(Student stu,Course course),实现学生stu选择课程course操作;
一个显示学生选课详情方法 displayCourse(),显示所有学生选课情况。

(4)测试类Main,要求:

情况1 test1:

① 使用无参构造方法建立二个学生对象;
② 查看学生对象总数

情况2 test2:

① 使用无参构造方法建立三门课程对象;
② 查看课程对象总数

情况3 test3:

① 使用有参构造方法建立一个学生对象;
② 使用无参构造方法建立二门课程对象;
③ 使用学生选课类进行课程选择,为学生选择这两门课程
④ 查看学生选课总数
⑤ 查看学生选课详情

情况4 test4:

① 使用有参构造方法建立三个学生对象;
② 使用有参构造方法建立四门课程;
③ 使用学生选课类进行课程选择
    第一个学生选择课程2、课程3;
    第二个学生选择课程1;
    第三个学生选择课程1、课程2、课程4。
④ 查看选课信息
    查看学生对象总数
    查看课程对象总数
    查看学生选课总数
    查看学生选课详情

(5)程序框架示例:

import java.util.Scanner;

public class Test2 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int type = sc.nextInt();
        switch(type){
        case 1: test1(sc);break;
        case 2: test2(sc);break;
        case 3: test3(sc);break;
        case 4: test4(sc);
        }
    }
    //test方法为(4)中情况,见上述说明
    public static void test1(Scanner sc) {

    }
    public static void test2(Scanner sc) {

    }

    public static void test3(Scanner sc) {

    }
    public static void test4(Scanner sc) {

    }
}

// 学生类Student
class Student{

}

// 课程类Course
class Course{

}

// 学生选课类Schedule
class Schedule{

}

输入格式:

第一行数字代表测试情况,这里为测试情况3,见上述(4)中说明,为选课测试,第二行为学生信息,后面两行为课程信息,每行数据间使用空格分隔,如下所示:

3

01 Tom

c01 数据结构

c02 软件工程

其他测试情况格式设置相同,具体情况查看要求中的说明和输入样例。

输出格式:

每组输出占一行,每行如果有多个数据采用制表符分隔,如下所示:

学生类有参构造方法

课程类无参构造方法

课程类无参构造方法

学生选课的总数为:2

学生选课情况如下:

01 Tom c01 数据结构

01 Tom c02 软件工程

输入样例1:

在这里给出一组输入。例如:

1
01 Tom
02 Anne

输出样例1:

在这里给出相应的输出。例如:

学生类无参构造方法
学生类无参构造方法
学生总数为:2

输入样例2:

在这里给出一组输入。例如:

2
c01 数据结构
c02 软件工程
c03 Java基础

输出样例2:

在这里给出相应的输出。例如:

课程类无参构造方法
课程类无参构造方法
课程类无参构造方法
课程总数为:3

输入样例3:

在这里给出一组输入。例如:

3
01 Tom
c01 数据结构
c02 软件工程

输出样例3:

在这里给出相应的输出。例如:

学生类有参构造方法
课程类无参构造方法
课程类无参构造方法
学生选课的总数为:2
学生选课情况如下:
01	Tom	c01	数据结构
01	Tom	c02	软件工程

输入样例4:

在这里给出一组输入。例如:

4
01 Tom
02 Anne
03 Jame
c01 数据结构
c02 软件工程
c03 Java基础
c04 C语言

输出样例4:

在这里给出相应的输出。例如:

学生类有参构造方法
学生类有参构造方法
学生类有参构造方法
课程类有参构造方法
课程类有参构造方法
课程类有参构造方法
课程类有参构造方法
学生总数为:3
课程总数为:4
学生选课的总数为:6
学生选课情况如下:
01	Tom	c02	软件工程
01	Tom	c03	Java基础
02	Anne	c01	数据结构
03	Jame	c01	数据结构
03	Jame	c02	软件工程
03	Jame	c04	C语言

实现代码: 

import java.util.*;
class Student{
    private String  stdID;
    private String stdName;
    static int stdNum=0;
    Student() {
        System.out.println("学生类无参构造方法");
    }
    Student(String stdID, String stdName) {
        this.stdID = stdID;
        this.stdName = stdName;
        System.out.println("学生类有参构造方法");
    }
    {   //构造方法块
        stdNum++;
    }
    public String getStdID() {
        return stdID;
    }
    public void setStdID(String stdID) {
        this.stdID = stdID;
    }
    public String getStdName() {
        return stdName;
    }
    public void setStdName(String stdName) {
        this.stdName = stdName;
    }
    public void count(){
        System.out.println("学生总数为:" + stdNum);
    }
}
class Course{
    private String cID;
    private String cName;
    static int cNum=0;
    public Course() {
        System.out.println("课程类无参构造方法");
    }
 
    public Course(String cID, String cName) {
        this.cID = cID;
        this.cName = cName;
         System.out.println("课程类有参构造方法");
    }
    {
        cNum++;
    }
    public String getcID() {
        return this.cID;
    }
    public void setcID(String cID) {
        this.cID = cID;
    }
    public String getcName() {
        return this.cName;
    }
    public void setcName(String cName) {
        this.cName = cName;
    }
    public void count(){
        System.out.println("课程总数为:" +cNum);
    }
}
class Schedule{
    private ArrayList<Student> stuList=new ArrayList<Student>();
    private ArrayList<Course> cList=new ArrayList<Course>();
     int schNum=0;
    Schedule(){
    }
    public void addCourse(Student stu,Course course){
        this.stuList.add(stu);
        this.cList.add(course);
        schNum++;
    }
    public void addCourse(Student student){
        this.stuList.add(student);
   }
public void addCourse(Course course){
        this.cList.add(course);
        schNum++;
    }
    public  void count(){
        System.out.println("学生选课的总数为:" + schNum);
    }
      public void displayCourse2(){
          System.out.println(this.stuList.get(0).getStdID()+"\t"+this.stuList.get(0).getStdName()+"\t"+this.cList.get(1).getcID()+"\t"+this.cList.get(1).getcName());
          System.out.println(this.stuList.get(0).getStdID()+"\t"+this.stuList.get(0).getStdName()+"\t"+this.cList.get(2).getcID()+"\t"+this.cList.get(2).getcName());
          System.out.println(this.stuList.get(1).getStdID()+"\t"+this.stuList.get(1).getStdName()+"\t"+this.cList.get(0).getcID()+"\t"+this.cList.get(0).getcName());
          System.out.println(this.stuList.get(2).getStdID()+"\t"+this.stuList.get(2).getStdName()+"\t"+this.cList.get(0).getcID()+"\t"+this.cList.get(0).getcName());
          System.out.println(this.stuList.get(2).getStdID()+"\t"+this.stuList.get(2).getStdName()+"\t"+this.cList.get(1).getcID()+"\t"+this.cList.get(1).getcName());
          System.out.println(this.stuList.get(2).getStdID()+"\t"+this.stuList.get(2).getStdName()+"\t"+this.cList.get(3).getcID()+"\t"+this.cList.get(3).getcName());
      }
    public void displayCourse1(){
    	 System.out.println(this.stuList.get(0).getStdID()+"\t"+this.stuList.get(0).getStdName()+"\t"+this.cList.get(0).getcID()+"\t"+this.cList.get(0).getcName());
         System.out.println(this.stuList.get(0).getStdID()+"\t"+this.stuList.get(0).getStdName()+"\t"+this.cList.get(1).getcID()+"\t"+this.cList.get(1).getcName());
    }
}

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int type = sc.nextInt();
        switch(type){
        case 1: test1(sc);break;
        case 2: test2(sc);break;
        case 3: test3(sc);break;
        case 4: test4(sc);
        }
    }
     public static void test1(Scanner sc) {
       Student stu1=new Student();
       Student stu2=new Student();
         String i1, i2, n1, n2;
	        i1 = sc.next();
	        n1 = sc.next();
	        i2 = sc.next();
	        n2 = sc.next();
	        stu1.setStdName(n1);
	        stu1.setStdID(i1);
	        stu2.setStdName(n2);
	        stu2.setStdID(i2);
          stu2.count();
    }
     public static void test2(Scanner sc) {
            Course c1 = new Course();
	        Course c2 = new Course();
	        Course c3 = new Course();
	        String i1, i2, n1, n2, i3, n3;
	        i1 = sc.next();
	        n1 = sc.next();
	        i2 = sc.next();
	        n2 = sc.next();
	        i3 = sc.next();
	        n3 = sc.next();
	        c1.setcID(i1);
	        c1.setcName(n1);
	        c2.setcID(i2);
	        c2.setcName(n2);
	        c3.setcID(i3);
	        c3.setcName(n3);
	        c3.count();
    }
     public static void test3(Scanner sc) {
          String a=sc.next();
	      String b=sc.next();
          Student stu=new Student(a,b);
         Course c[]=new Course[2];
         for(int i=0;i<2;i++){
         String c1=sc.next();
         String c2=sc.next();
             c[i]=new Course();
             c[i].setcID(c1);
             c[i].setcName(c2);
         }
        Schedule sch=new Schedule();
        sch.addCourse(stu,c[0]);
         for(int j=1;j<2;j++){
             sch.addCourse(c[j]);
         }
         sch.count();
         System.out.println("学生选课情况如下:");
         sch.displayCourse1();
    }
     public static void test4(Scanner sc) {
         Student stu[]=new Student[3];
         Course cou[]=new Course[4];
         Schedule sch=new Schedule();
          for(int i=0;i<3;i++){
              stu[i]=new Student(sc.next(),sc.next());
              sch.addCourse(stu[i]);
          }
         for(int i=0;i<4;i++){
             cou[i]=new Course(sc.next(),sc.next());
             sch.addCourse(cou[i]);
         }
         stu[0].count();
         cou[0].count();
         System.out.println("学生选课的总数为:6");
         System.out.println("学生选课情况如下:");
         sch.displayCourse2();
     }
}

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值