2021级Java程序设计课程练习题

一、判断题

1-1 抽象类是不能实例化的。 T 

1-2 JAVA抽象类中一定含有抽象方法。 F 

答题时没有看到一定qaq,抽象类不一定包含抽象方法,但包含抽象方法的类一定是抽象类。

二、单选题

2-2 有如下程序代码, 程序运行的结果是( )。

String s1 = "sdut";
String s2 = "I love " + s1;
String s3 = "I love " + s1;
System.out.print(s2 == s3);
Sytem.out.println(" "+s2.equals(s3));

D.false true

第一个竟然是false!!!

使用“==”比较两个字符串,是比较两个对象的地址是否一致,本质是判断两个变量是否指向同一个对象;String类的equals方法是比较两个字符串的内容是否一致,返回值也是一个bool类型。

2-2 关于字符串的方法,如下代码执行结果是( )。

String str = "    abcd123";
  str.toUpperCase();
  str.trim();
  System.out.println(str);

A.“    abcd123

两个方法未对str进行赋值;

toUpperCase对StringObject的所有小写字符全部转换为大写字符

trim方法删除stringObject的头尾空白符(仅有头尾)。

三、填空题

3-1 在映射(Map)集合中查找指定关键字的元素

本题目要求输入关键字,在映射(Map)集合中进行查找。

import java.util.*;
/* 这里是 People 类代码,无需关心
 */
public class Main
{
    public static void main(String args[])
    {
        Map<String,People> peoples = new HashMap<String,People>();
        peoples.put("rose", new People("rose",18));
        peoples.put("hunifu", new People("hunifu",19));
        peoples.put("hunifu", new People("britsh",20));
        if(①) //@@正确判断 Map 元素个数
        { 
            Scanner sc=new Scanner(System.in);
            //通过new Scanner(System in)创建一个Scanner,控制台会一直等待输入
            String key=sc.next();
            if(②)//@@判断关键字是否存在 Map 内 
                System.out.println(③);//@@取出关键字指定元素 
            else 
                System.out.println("映射中不存在 key ="+key+" 的元素"); 
        } 
    } 
}

①peoples.size() > 0 

②peoples.containsKey(key)

③peoples.get(key)

https://blog.csdn.net/m0_66298628/article/details/125237634

Java中super()的使用_程序员资料站的博客-CSDN博客_super()

3-2 类和对象的创建和使用

定义一个Person类,该类包括age,name两个数据成员和eat(),work()两个成员方法,并实现对两个数据成员的Getter方法。然后通过测试程序,实现相应对象的操作。程序输出结果如下:

请按提示完善相应的程序。

class Person
{
    public int age;             //声明公共字段age
    ①; //声明私有字段name
    public int getAge()//实现age成员的Getter方法
    {
        return age;
    }
    public String getName() //实现name成员的Getter方法
    {
        ②;
    }
    public void eat() //定义无参数的eat方法
    {
        System.out.println(③);
    }
    public void work(String s) //定义带参数的work方法
    {
        System.out.println("努力创造"+s);
    }
    public Person(int age, String name) //定义一个带参数构造函数
    {
         this.age = age; this.name = name;
    }
}
public class Main
{
    public static void main(String[] args)
    {
        Person p =④(18, "张三");//调用类的有参构造函数
        System.out.println("姓名:"+p.getName()+"\n年龄:" + p.getAge());
        ⑤; //调用对象的eat方法
        p.work("美好生活");
    }
}

①private String name

②return name

③"会生活"

④new Person

⑤p.eat()

3-3 计算每个雇员每周工作的小时数并排序

假定所有雇员每周工作的小时数存储在一个二维数组中。1行包含7列,记录了一个雇员7天的工作小时数。编写一个程序,按照总工时降序的方式显示雇员和他们的总工时。

public class Main
{
    /** Main method */
    public static void main(String[] args)
    {
        // Declare, create, and initialized array
        double[][] workHours =
                {
                {2, 4, 3, 4, 5, 8, 8},
                {7, 3, 4, 3, 3, 4, 4},
                {3, 3, 4, 3, 3, 2, 2},
                {9, 3, 4, 7, 3, 4, 1},
                {3, 5, 4, 3, 6, 3, 8},
                {3, 4, 4, 6, 3, 4, 4},
                {3, 7, 4, 8, 3, 8, 4},
                {6, 3, 5, 9, 2, 7, 9}
                };
        // Create an array to store total weekly hours
        int[] weeklyHours = new int[workHours.length];
        for (int i = 0; i < workHours.length; i++)
            for (int j = 0; j < workHours[i].length; j++)
                weeklyHours[i] += ①;
        int[] indexList = new int[weeklyHours.length];
        // Sort weeklyHours
        sortAndKeepIndex(weeklyHours, indexList);
        // Display result
        for (int i = weeklyHours.length - 1; i >= 0; i--)
            System.out.println("Employee " + indexList[i] + ": " +②);
    } 
    /** The method for sorting the numbers */ 
    static void sortAndKeepIndex(int[] ③,④indexList)
    { 
        int currentMax; int currentMaxIndex;
        // Initialize indexList 
        for (int i = 0; i < indexList.length; i++) 
            indexList[i] = i; 
        for (int i = list.length - 1; i >= 1; i--) 
        { 
            // Find the maximum in the list[0..i] 
            currentMax = list[i]; 
            currentMaxIndex = ⑤;
            for (int j = i - 1; j >= 0; j--) 
            { 
                if (currentMax < list[j]) 
                { 
                    currentMax = ⑥;
                    currentMaxIndex = j; 
                } 
            } 
            // Swap list[i] with list[currentMaxIndex] if necessary; 
            if (currentMaxIndex != i) 
            { 
                list[currentMaxIndex] = list[i]; 
                list[i] = currentMax; 
                // Swap the index in indexList too 
                int temp = ⑦;
                ⑧ = indexList[currentMaxIndex]; 
                indexList[currentMaxIndex] = temp; 
            } 
        } 
    } 
}

workHours[i][j]

weeklyHours[i]

list

int[]

indexList[i]

list[j]

indexList[i]

indexList[i]

3-4 矩形类

构造一个Rectangle类表示矩形 , 该类实现了Comparable接口。

  • 该类有两个私有的double型成员变量width和height,表示矩形的宽度和高度;
  • 该类有一个带一个无参的构造方法,把宽带和高度都初始化为0;
  • 该类有一个带两个double型参数的构造方法,用参数的值初始化矩形的宽度和高度。
  • 为width和height添加getter()和setter()方法。注意,宽度和高度必须大于等于0,如果setWidth(double width)方法的参数小于0时,抛出一个IllegalArgumentException异常对象,异常对象的成员变量message为"矩形的宽度必须大于等于0";setHeight(double height)方法的参数小于0时,抛出一个IllegalArgumentException异常对象,异常对象的成员变量message为"矩形的高度必须大于等于0"。
  • getArea()方法,返回矩形的面积;
  • getgetPerimeter()方法,返回矩形的周长;
  • 该类有一个公共的方法int compareTo(Rectangle rectangle),比较当前对象和参数。如果当前对象的面积大于参数的面积,返回1;当前对象的面积小于参数的面积,返回-1;否则返回0。
  • 该类有一个公共方法toString(),根据矩形的宽度和高度生成并返回一个字符串(具体要求看输出样例)。

构造一个Main ,执行一个for循环,共循环6次。每次循环从键盘读入数据创建两个矩形对象,比较并输出其中较大的对象的面积;如果捕捉到异常,则输出异常信息。

①
public class Main
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        for(int i=0; i<6; i++)
        {
            ②
            {
                Rectangle rectangle1 = new Rectangle(input.nextDouble(), input.nextDouble());
                Rectangle rectangle2 = new Rectangle(input.nextDouble(), input.nextDouble());
                ③
                if (rectangle1.④(rectangle2)>= 0)
                    ⑤
                else
                    ⑥
                System.out.println("The max area of " + rectangle1 + " and " + rectangle2 + " is " + maxRectangle.getArea());
            }
            ⑦(IllegalArgumentException e1)
            {
                System.out.println(e1.getMessage());
                input.nextLine();
            }
            catch (Exception e2)
            {
                System.out.println(e2.getMessage());
                input.nextLine();
            }
        }
    }
}

interface Comparable
{
    public double getWidth();
    public void setWidth(double width);
    public double getHeight();
    public void setHeight(double height);
    public double getArea();
    public double getPerimeter();
    public int compareTo(Rectangle rectangle);
    public String toString();
}

class Rectangle ⑧
{
    private double width;
    private double height;
    public ⑨()
    {
        width=0;
        height=0;
    }
    public Rectangle(double width, double height)
    {
        ⑩(width);
        ⑾(height);
    }
    public double getWidth()
    {
        return width;
    }
    public void setWidth(double width)
    {
        if(⑿)
            this.width = width;
        else
            ⒀
    }
    public double getHeight()
    {
        return height;
    }
    public void setHeight(double height)
    {
        if(⒁)
            this.height = height;
        else
            ⒂
    }
    public double getArea()
    {
        ⒃
    }
    public double getPerimeter()
    {
        ⒄
    }
    public int compareTo(Rectangle rectangle)
    {
        if (⒅)
            return 1;
        else
            if (十九)
                return -1;
            else
                return 0;
    }
    public String toString()
    {
        return 二十
    }
}

接口Comparable为我另加的,因为题目中提到Rectangle类实现了Comparable接口,但Java中没有提供Comparable接口,需要自己定义;①Comparable中的各种方法不写也可以;②如果在Comparable前加上public,不论加在interface前面还是后面,如果写所有方法的声明都会显示错误java: 需要<标识符>;如果不在Comparable接口中写方法的声明,显示错误java: 接口 Comparable 是公共的, 应在名为 Comparable.java 的文件中声明

Java 接口与实现(详细版) (baidu.com)

类接口_qppan_wx的博客-CSDN博客_类接口

1、import java.util.*;

2、try

3、Rectangle maxRectangle;

4、compareTo

5、maxRectangle=rectangle1;

6、maxRectangle=rectangle2;

7、catch 

8、implements Comparable<Rectangle>

9、Rectangle

10、setWidth

11、setHeight

12、width>=0

13、throw new IllegalArgumentException("矩形的宽度必须大于等于0");

14、height>=0

15、throw new IllegalArgumentException("矩形的高度必须大于等于0");

16、return width*height;

17、return 2*(width+height);

18、getArea()>rectangle.getArea()

19、getArea()<rectangle.getArea()

20、"Rectangle(width:" + width + ",height:" +height + ")";

IllegalArgumentException(非法参数异常)和其子类异常NumberFormatException,以及异常类之间的继承关系和产生原因_是小陈呀~的博客-CSDN博客_illegalargument

上面这一个没有看明白,下面第一个是对上面那个暂时没看懂的辅助

radix在Character.MIN_RADIX与Character.MAX_RADIX之间_ROBIN-KING的博客-CSDN博客_character.max_radix

Java中import java.util.Scanner;语句的作用_不爱吃番茄aa的博客-CSDN博客_import java.util.scanner;

try-catch的使用以及细节_呀吖呀吖呀的博客-CSDN博客_try-catch

5-5 自定义异常类:成绩异常(ScoreException)

自定义一个异常类ScoreException,继承自Exception类。有一个私有的成员变量message(异常提示信息,String类型);一个公有的无参数的构造方法,在方法中将message的值确定为“您输入的成绩异常,请核实!”;一个公有的方法show(),该方法的功能是输出message的值。

定义一个学生类Student,有一个私有成员变量score(成绩,double类型);一个带参数的公有方法setScore()用于设置学生的成绩,该方法声明可能抛出异常ScoreException,当设置的成绩为负数或超过100时,会抛出一个异常对象;一个公有方法getScore()用于获取学生的成绩。

在测试类Main中,创建一个Student类的对象zhangsan,尝试调用setScore()方法来设置他的成绩(成绩从键盘输入,double类型),然后调用getScore()方法获取到该成绩后再将其输出。因用户的输入存在不确定性,以上操作有可能捕捉到异常ScoreException,一旦捕捉到该异常,则调用show()方法输出异常提示。不管是否有异常,最终输出“程序结束”。使用try...catch...finally语句实现上述功能。

import java.util.Scanner;

class ScoreException ①
{
    private String message;
    public ScoreException()
    {
        message = "您输入的成绩异常,请核实!";
    }
    public void show()
    {
        System.out.println(message);
    }
}
class Student
{
    private double score;
    public void setScore(double score) throws ScoreException
    {
        if (score<0 || score>100)
            throw ②;
        else
            ③;
    }
    public double getScore()
    {
        return this.score;
    }
}
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        Student zhangsan = new Student();
        ④
        {
            zhangsan.setScore(sc.nextDouble());
            System.out.println("成绩为" + zhangsan.getScore());
        }catch(ScoreException e)
        {
            e.show();
        }finally
        {
            ⑤;
        }
        sc.close();
    }
}

①extends Exception

②new ScoreException()

③this.score = score

④try

⑤System.out.println("程序结束")

3-6 this在构造方法的使用

class Base
{ 
    int x, y, z, w;

    public Base(int a, int b)
    {
        x = a;
        y = b;
    }

    public Base(int a, int b, int c, int d)
    {
        // 换一种办法实现赋值x=a, y=b 
        ①
        
        z = c;
        w = d;
    }
}

public class Main
{
    public static void main(String[] args)
    {
        Base base = ②(1, 1, 1, 1);
        System.out.println(base.x + " " + base.y + " " + base.z + " " + base.w);
    }
}

java构造方法中this_Java中this关键字在构造方法中的使用_瓜呼呼的博客-CSDN博客

 1、this(a,b);

2、 new Base

四、函数题

4-1 学生类

设计一个名为StudentOf2019EE的类,表示2019电子信息工程专业的学生。类包含:

  • String类型私有成员变量name,表示学生的姓名。
  • int型私有成员变量money,表示学生可支配的金额(不能为负数)。
  • int型私有静态(类)变量numberOfObjects,表示StudentOf2019EE对象的数量,初始值为0;每创建一个StudentOf2019EE对象,numberOfObjects应当加1。
  • int型私有静态(类)变量clazzMoney,表示全体学生缴纳的班费余额,初始值为0。
  • 构造方法StudentOf2019EE(String name),参数name用于初始化学生的姓名,可支配金额设为默认值100。
  • 构造方法StudentOf2019EE(String name, int mongey),参数name用于初始化学生的姓名,参数money用于初始化学生的可支配金额。
  • 为name和money添加getter和setter方法,都为公共方法。
  • 公共的实例方法void payClazzMoney(int amount),表示从学生的可支配金额中支出数量为amount的金额作为班费(如果学生的可支配金额<amount,则有多少交多少班费)。
  • 公共的静态方法void clazzActivity(int amount),表示班级活动,需要从班费余额支出数量为amount的金额作为活动经费(如果班费余额<amount,则有多少支出多少)。

创建三个StudentOf2019EE对象,三个对象分别支付一笔钱作为班费,最后组织一次班级活动。

裁判测试程序样例:

import java.util.Scanner;

public class Main {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.println("numberOfObjects=" + StudentOf2019EE.getNumberOfObjects() + ",clazzMoney=" + StudentOf2019EE.getClazzMoney());

        StudentOf2019EE a = new StudentOf2019EE("Tom");
        StudentOf2019EE b = new StudentOf2019EE("Jerry", 200);
        StudentOf2019EE c = a;

        a.payClazzMoney(input.nextInt());
        System.out.println("numberOfObjects=" + StudentOf2019EE.getNumberOfObjects() + ",clazzMoney=" + StudentOf2019EE.getClazzMoney());

        b.payClazzMoney(input.nextInt());
        System.out.println("numberOfObjects=" + StudentOf2019EE.getNumberOfObjects() + ",clazzMoney=" + StudentOf2019EE.getClazzMoney());

        c.payClazzMoney(input.nextInt());
        System.out.println("numberOfObjects=" + StudentOf2019EE.getNumberOfObjects() + ",clazzMoney=" + StudentOf2019EE.getClazzMoney());

        StudentOf2019EE.clazzActivity(input.nextInt());
        System.out.println("numberOfObjects=" + StudentOf2019EE.getNumberOfObjects() + ",clazzMoney=" + StudentOf2019EE.getClazzMoney());
    }
}

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

输入样例:

50

300

100

400

输出样例:

numberOfObjects=0,clazzMoney=0
numberOfObjects=2,clazzMoney=50
numberOfObjects=2,clazzMoney=250
numberOfObjects=2,clazzMoney=300
numberOfObjects=2,clazzMoney=0
 

代码长度限制:16 KB

时间限制:800 ms

内存限制:64 MB

class StudentOf2019EE
{
    private String name;
    private int money;
    private static int numberOfObjects = 0;
    private static int clazzMoney = 0;
    StudentOf2019EE(String name)
    {
        numberOfObjects++;
        this.name = name;
        money = 100;
    }
    StudentOf2019EE(String name, int mongey)
    {
        numberOfObjects++;
        this.name = name;
        this.money = mongey;
    }

    public int getMoney()
    {
        return money;
    }

    public String getName()
    {
        return name;
    }

    public void setMoney(int money)
    {
        this.money = money;
    }

    public void setName(String name)
    {
        this.name = name;
    }
    public void payClazzMoney(int amount)
    {
        if(this.money < amount)
        {
            clazzMoney += money;
            money = 0;
        }else
        {
            clazzMoney += amount;
            money -= amount;
        }
    }
    static public void clazzActivity(int amount)
    {
        if(clazzMoney < amount)
        {
            clazzMoney = 0;
        }else
        {
            clazzMoney -= amount;
        }
    }
    static public int getNumberOfObjects()
    {
        return numberOfObjects;
    }

    static public int getClazzMoney()
    {
        return clazzMoney;
    }
}

 4-2 圆和圆柱体1

编写一个Java程序,包含类Circle、Cylinder、Main,其中Main已经实现,请你编写Circle和Cylinder类。

(1)编写类Circle,表示圆形对象,包含以下成员

①属性: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)编写一个Circle类的子类Cylinder,表示圆柱形对象,包含以下成员

①属性:height:私有,double型,圆柱体高度;

②方法:

  1. Cylinder(double radius,double height), 构造方法,用参数设置圆柱体的半径和高度
  2. Cylinder(),构造方法,将圆柱体的半径和高度都初始化为0。
  3. void setHeight(double height):用参数height设置圆柱体的高度
  4. double getHeight():返回圆柱体的高度
  5. double getArea(),重写Circle类中的area方法,返回圆柱体的表面积
  6. double getVolume(),返回圆柱体的体积
  7. public String toString( ),将把当前圆柱体对象的转换成字符串形式,例如半径为10.0,高为5.0,返回字符串"Cylinder(r:10.0,h:5.0)"。

输入格式:

第一行输入一个整数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.1592653589793
The perimeter of Circle(r:10.0) is 62.83185307179586
The area of Cylinder(r:10.0,h:10.0) is 1256.6370614359173
The volume of Cylinder(r:10.0,h:10.0) is 3141.5926535897934
The area of Circle(r:1.1) is 3.8013271108436504
The perimeter of Circle(r:1.1) is 6.911503837897546
The area of Cylinder(r:1.1,h:3.4) is 31.101767270538957
The volume of Cylinder(r:1.1,h:3.4) is 12.924512176868411
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

class Circle
{
    private double radius;//圆形半径

    Circle(double radius)
    {
        this.radius  = radius;
    }

    Circle()
    {
        radius = 0;
    }

    void setRadius(double r)
    {
        this.radius = r;
    }

    double getRadius()
    {
        return radius;
    }

    double getArea()
    {
        return radius * radius * Math.PI;
    }

    double getPerimeter()
    {
        return  2 * Math.PI * radius;
    }

    public String toString( )
    {
        return "Circle(r:" + radius + ")";
    }
}

class Cylinder extends Circle
{
    private double height;

    Cylinder(double radius,double height)
    {
        setRadius(radius);
        this.height = height;
    }

    Cylinder()
    {
        setRadius(0);
        this.height = 0;
    }

    void setHeight(double height)
    {
        this.height = height;
    }

    double getHeight()
    {
        return height;
    }

    double getArea()
    {
        return 2 * getRadius() * Math.PI * getRadius() + 2 * Math.PI * getRadius() * height;
    }

    double getVolume()
    {
        return getRadius() * Math.PI * getRadius() * height;
    }

    public String toString( )
    {
        return "Cylinder(r:" + getRadius() + ",h:" + height + ")";
    }
}

 4-3 根据要求,使用泛型和LinkedList编写StringList类,实现QQ号码查找的功能。

已知数组存放一批QQ号码,QQ号码最长为11位,最短为5位:
String[] strs = {"12345","67891","12347809933","98765432102","67891","12347809933"}。
将该数组里面的所有QQ号都存放在LinkedList中,然后遍历链表,将list中第一个指定长度的QQ号查找出来;如果不存在指定长度的QQ号,则输出“not exist”。

Main类:在main方法中,调用constructList方法将strs中的字符串存入一个String的链表中,然后调用search方法查找第一个指定长度的QQ号码,并打印到屏幕。

编写StringList类,编程要求如下:

  1. 根据程序需求,定义成员变量、编写构造方法。
  2. LinkedList constructList(String[] strs) 方法:将String数组strs中的元素添加到链表中,构建一个String对象链表,最后返回链表。
  3. String search(LinkedList list)方法:使用scanner的nextInt()方法从键盘读入一个int,表示指定长度,然后遍历链表,查找出链表中第一个指定长度的QQ号码并返回;如果不存在指定长度的QQ号,则返回字符串"not exist"。

函数接口定义:

LinkedList<String> constructList(String[] strs);
String search(LinkedList<String> list);

裁判测试程序样例:

import java.util.*;

public class Main {    
    public static void main(String[] args) {
        String[] strs = {"12345","67891","12347809931","98765432102","67891","12347809933"};
        StringList sl=new StringList();
        LinkedList<String> qqList=sl.constructList(strs);
        System.out.println(sl.search(qqList));
    }
}
    
/* 请在这里填写答案:StringList类 */

输入样例:

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

5
 

输出样例:

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

12345
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

Java 建立一个单链表(增删查改)_爱干饭的猿的博客-CSDN博客_java new一个链表

class StringList
{
    StringList()
    {}

    LinkedList<String> constructList(String[] strs)
    {
        LinkedList<String> list = new LinkedList<String>();
        for(int i=0; i< strs.length;i++)
        {
            list.add(strs[i]);
        }
        return list;
    }

    String search(LinkedList<String> list)
    {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        Iterator it = list.iterator();
        while (it.hasNext())
        {
            String str = (String) it.next();
            if(a == str.length())
            {
                return str;
            }
        }
        return "not exist";
    }
}

 简化了一下下面的代码2021-06-11_dada dog的博客-CSDN博客_编写一个程序,其中提供linkedlist链表,用来保存班级同学的qq号,假设qq号都是8位数

String str = it.next();如果不在it前面加(String)会显示错误ava: 不兼容的类型: java.lang.Object无法转换为java.lang.String

4-4  jmu-Java-06异常-finally

代码中向系统申请资源,到最后都要将资源释放。

现有一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
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

除了题目要我们写的代码,这个代码还有其他地方也要补一下

miao

import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        Resource resource = null;
        try {
            resource = new Resource();
            resource.open(sc.nextLine());
            /*这里放置你的答案*/
            System.out.println("resource open success");
        }catch (Exception e)
        {
            System.out.println(e);
        }
        try
        {
            sc.close();
            System.out.println("resource release success");
        }catch(RuntimeException e)
        {
            System.out.println(e);
        }
    }
}
class Resource
{
    public open(String s)
    {

    }
}

 4-5 Java-函数题-1(字符串查询)

本题要求实现一个函数,可统计任一字符串中某个字符出现的次数。例如 abca 中,a 出现了 2 次,b 出现了 1 次。

函数接口定义:

函数的原型如下:
public static int countChar(String string, char c);
 

其中 string 和 c 都是用户传入的参数。

string 的长度在区间 [1,1000] 以内; c 是一个可能出现在字符串中的字符。函数须返回 string 中 c 出现的次数。

裁判测试程序样例:

在这里给出函数被调用进行测试的例子。例如:
import java.util.*;

public class Main {

/* 此区间是要编写的函数 */
    public static int countChar(String string, char c) {
        //请补充完整
    }
/* 此区间是要编写的函数 */

    public static void main(String[] args) {
        Scanner key = new Scanner(System.in);
        String s1 = key.nextLine();
        String s2 = key.nextLine();
        System.out.println(countChar(s1, s2.charAt(0)));
    }
}

输入样例:

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

abca
a
 

输出样例:

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

2
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

 这题有毛病,还得加上函数名才正确,但题目中不是给了吗,难搞、

Java基础---字符串之如何比较字符串_Tan.]der的博客-CSDN博客_字符和字符串怎么比较

Java中字符串比较/字符比较_NJUSTZJC的博客-CSDN博客

注意分清字符数组与字符串的区别

public static int countChar(String string, char c)
    {
        //请补充完整
        int a = 0;
        for(int i=0;i<string.length();i++)
        {
            if(c == string.charAt(i))
                a++;
        }
        return a;
    }

4-6 数组求和

编写程序。读入用户输入的10个整数存入数组中,并对数组求和。

要求实现3个数组求和方法。

//求数组a中所有元素的和
static int sum(int[] a){

}

//求数组a中下标从start开始到数组末尾的元素的和
static int sum(int[] a, int start){

}

//求数组a中下标从start开始到end-1的元素的和
static int sum(int[] a, int start, int end){

}

裁判测试程序样例:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] a = new int[10];
        int start,end;

        for(int i = 0;i < a.length; i++){
            a[i] = input.nextInt();
        }

        System.out.println(sum(a));

        start = input.nextInt();
        System.out.println(sum(a, start));
            
        start = input.nextInt();
        end = input.nextInt();
        System.out.println(sum(a, start, end));
    }
    
      /* 请在这里填写答案 */
}

输入样例:

1 2 3 4 5 6 7 8 9 10
5
5 8
 

输出样例:

55
40
21
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

 PTA非零返回的解决办法java_两条鱼h的博客-CSDN博客_非零返回

第一次非零返回

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

    //求数组a中下标从start开始到数组末尾的元素的和
    static int sum(int[] a, int start)
    {
        int sum = 0;
        for(int i = start; i<a.length;i++)
        {
            sum += a[i];
        }
        return  sum;
    }

    //求数组a中下标从start开始到end-1的元素的和
    static int sum(int[] a, int start, int end)
    {
        int sum = 0;
        for(int i =start;i<end;i++)
        {
            sum += a[i];
        }
        return sum;
    }

 第二次对了

 static int sum(int[] a)
    {
        int sum = 0;
        int c = a.length;
        for(int i=0;i<c;i++)
        {
            int b = a[i];
            sum += b;
        }
        return sum;
    }

    //求数组a中下标从start开始到数组末尾的元素的和
    static int sum(int[] a, int start)
    {
        int sum = 0;
        int c = a.length;
        int d = 0;
        if(start >= 0)
             d = start;

        for(int i = d; i<c;i++)
        {
            int b = a[i];
            sum += b;
        }
        return  sum;
    }

    //求数组a中下标从start开始到end-1的元素的和
    static int sum(int[] a, int start, int end)
    {
        int sum = 0;
        int c = a.length;
        int d = 0;
        if(start >= 0)
            d = start;
        for(int i = d;i<=end-1&&i<c;i++)
        {
            int b = a[i];
            sum += b;
        }
        return sum;
    }

         原来返回非零是指数组越界了

五、编程题

5-1  sdut-最大公约数和最小公倍数

给定2个正整数,求它们的最大公约数和最小公倍数,并输出。

输入格式:

输入有若干组。

每组数据,在一行中给出两个正整数M和N(≤1000),中间有1个空格。

不是有若干组测试样例,而是一组测试样例里面有若干组输入;

输出格式:

对于每组输入,在一行中顺序输出M和N的最大公约数和最小公倍数,两数字间以1个空格分隔。

输入样例:

18 12
20 15
39 26
5 76
45 25
1993 343
 

输出样例:

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

6 36
5 60
13 78
1 380
5 225
1 683599
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

first提交

偷了下懒,结果有时间限制


import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt())
        {
        int a = sc.nextInt();
        int b = sc.nextInt();
        int min,max;
        if(a >= b)
        {
            min =a;
            max = b;
        }else
        {
            min = b;
            max = a;
        }
        for(;max>1;max--)
        {
            if(a%max==0&&b%max==0)
                break;;
        }
        for(;;min++)
        {
            if(min%a==0&&min%b==0)
                break;;
        }
        System.out.println(max+" "+min);
        }
    }
}

最后提交

C++之 最大公约数求法_ililily的博客-CSDN博客_c++最大公约数

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt())
        {
            int a = sc.nextInt();
            int b = sc.nextInt();

            int c = a;
            int d = b;
            int min,max;

            int r = a % b;
            while (r!=0)
            {
                a = b;
                b = r;
                r = a % b;
            }


                min = (c/b) * (d/b) * b;


            System.out.println(b+" "+min);
        }

    }
}

5-2 java编程判断斐波那契数是质数

斐波那契数列(FibonacciSequence),又称黄金分割数列。因数学家列昂纳多·斐波那契(LeonardoFibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:1, 1, 2, 3, 5, 8, 13, 21, 34 ⋯

在数学上,斐波那契数列被以如下的递推形式定义:

F(1)=1,F(2)=1
F(n)=F(n−1)+F(n−2),(n≥3,n∈N)

素数也称为质数,是指在大于 1 的整数中,只能被 1 和其自身整除的数,2 是最小的质数。

我们想要知道斐波那契数列的第 n 项是否是一个素数,请你编写程序完成判断。

输入格式:

一行,一个整数 n(1≤n≤50)

输出格式:

一行,一个单词,如果 F(n) 是素数,输出true,反之输出false

输入样例1:

1
 

输出样例1:

false
 

输入样例2:

2
 

输出样例2:

false
 

输入样例3:

3
 

输出样例3:

true
 

代码长度限制:16 KB

时间限制:2000 ms

内存限制:64 MB

 第一次只对了一个,而且题目中有错误,2不是素数,但题目把他归为素数;

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();

        int num = feb(a);

        if(num == 2)
        {
            System.out.println("false");
        }else if(num % 2 == 0)
        {
            System.out.println("true");
        }else
        {
            double b = Math.sqrt(num);
            for (int i = 3;i<b;i=i+2)
            {
                if(num % i == 0)
                {
                    num = 0;
                    break;
                }
            }
            if(num == 0)
            {
                System.out.println("true");
            }else
                System.out.println("false");
        }
    }
    public static int feb(int i)
    {

        // 第一种情况,前两个默认的数字 均为1。
        if(i == 1 || i == 2){
            return 1;
        }else
        {
            // 第二种情况,返回前两个数之和
            return feb(i - 1) + feb(i - 2);
        }
    }
}

 1、大于五十的数应该返回零

2、用递归的方式求斐波那契数列会耗费时间

3、这个是判断是否是素数,判断结果写反了

最后一次提交

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int num = 0;
        int u = 0, k = 1;
        if(a<=50&&a>=1)
        {
            for(int i=1;i<=a;i++)
            {
                u = num;
                num = k + num;
                k = u;
            }
            if(num == 2)
            {
                System.out.println("true");
            }else if(num % 2 == 0)
            {
                System.out.println("false");
            }else
            {
                double b = Math.sqrt(num);
                for (int i = 3;i<b;i=i+2)
                {
                    if(num % i == 0)
                    {
                        num = 0;
                        break;
                    }
                }
                if(num == 0)
                {
                    System.out.println("false");
                }else
                    System.out.println("true");
            }

        }
    }

}

5-3 统计学生年龄异常的人数

定义Student类:

(1)成员变量有:姓名,年龄。
(2)对成员变量进行封装。
(3)定义getXXXX,setXXXX方法,其中对年龄的限定条件是:年龄大于0。
 

定义主类,包含主方法:

实现输入5个学生,输出年龄不符合要求 的学生人数和姓名。
如果年龄全部正确,输出“right”,如果全部错误,输出"all wrong"。
 

输入格式:

5行,每行1个学生信息,包括姓名和年龄

输出格式:

多行,第1行是不符合要求的人数
其余各行是不符合要求的学生的姓名
如果年龄全部正确,输出“right”,如果全部错误,输出"all wrong"。

输入样例:

zhang 18
Li -15
wang 0
zhao 20
wu -20
 

输出样例:

3
Li
wang
wu
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

import  java.util.Scanner;

public class Main
{
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        String a[] = new String[5];
        int b[] = new int[5];
        for(int i = 0;i < 5;i++)
        {
            a[i] = sc.next();
            b[i] = sc.nextInt();
            Student stu = new Student(a[i],b[i]);
        }
        if(Student.num == 0)
        {
            System.out.println("right");
        }
        else if(Student.num == 5)
        {
            System.out.println("all wrong");
        }
        else
        {
            System.out.println(Student.num);
            for(int j = 0;j < 5;j++)
            {
                if(b[j]<=0)
                    System.out.println(a[j]);
            }
        }
    }
}


class Student
{
    private String name;
    private int age;
    static int num = 0;
    //成员
    public Student() {}
    public Student(String name,int age)
    {
        this.name=name;
        this.age=age;
        if(age <= 0)
            num++;
    }
    //构造
    public String getname() 
    {
        return this.name;
    }
    public int getage() 
    {
        return this.age;
    }
    public void setname(String name) 
    {
        this.name = name;
    }
    public void setage(int age)
    {
        this.age = age;
    }//get   set   
}

 5-4 jmu-java-随机数-使用蒙特卡罗法计算圆周率的值

尝试使用蒙特卡罗法计算圆周率(π)的值。原理如下:

以原点(0, 0)作为圆心,半径为1画一个圆。该圆的外切正方形,边长为2。

现往该正方形内随机投点,数量足够多的情况下,落入圆内的点与落入整个
外切正方形的点的数量比值大概为: 4∗r2π∗r2​,然后就可以得到π的值。

注意

  1. 请使用jdk库中的Random对象来生成随机数。
  2. 使用Math类中的sqrt与pow函数来计算开根号与平方值。
  3. 让点(x,y)投在整个矩形中,x与y的取值范围为(-1≤x<1, -1≤y<1)。

输入格式:

随机数种子seed 投点个数n
注意:seed为long型,n为int型

输出格式:

计算出的值圆周率的值

输入样例:

2 100000
 

输出样例:

3.14684
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

import java.util.Random;
import java.util.Scanner;

/**
 *
 * @author 梓叶枫林
 * @date 2020/10/28
 */
public class Main {

    public static void main (String [] args) {

        Scanner scanner = new Scanner(System.in);
        long seed = scanner.nextLong();
        int n = scanner.nextInt();
		scanner.close();
        //将随机数种子放入随机数中
        Random random = new Random(seed);

        int insideNum = 0;

        for (int i = 0; i < n; i++) {

            //random.nextDouble()的值域[0.0, 1.0)。要使函数为[-1.0, 1.0),所以进行了下面的操作。
            double x = random.nextDouble() *2 - 1;
            double y = random.nextDouble() *2 - 1;

            //记录点在圆内的数量
            if (Math.pow(x, 2) + Math.pow(y, 2) <= 1) {
                insideNum++;
            }
        }
        //从所给的公式 反推出PI的公式
        //需要把insideNum强转成double,不然整数相除会出错
        System.out.println(4 * ((double) insideNum / n));
    }
}

 5-5 定义学生类覆盖Object中的方法实现Comparable接口

定义一个学生类Student,成员变量包括:姓名,生日,学号,学校;重写方法toString,equals,hashCode;实现接口Comparable,按照学号大小进行比较;定义构造方法。
代码形式如下:

public class Main{
public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int num=in.nextInt();
        Student[] studentArray = new Student[num];
        for(int i=0;i<num;i++)
        {
            String name=in.next();
            int year=in.nextInt();
            int month=in.nextInt();
            int day=in.nextInt();
            String studentId=in.next();
            String school=in.next();
            studentArray[i]=new Student(name,year,month,day,studentId,school);
        }
        
        Arrays.sort(studentArray);
        for(Student s:studentArray)
            System.out.println(s);
    }
}
class Student implements Comparable
{
  //给出Student的定义
}

输入格式:

第一行输入学生人数。其他各行每行输入一个学生的姓名,出生年月日,学号,学号,用空格分隔。

输出格式:

按照学号从小到大排序的学生信息,每个学生信息一行。

输入样例:

例如:

3
李翔 2002 10 9 202019001  北京化工大学
张凯 2002 11 23 202019015  北京化工大学
汪海 2002 7 5 202019012  北京化工大学

输出样例:

例如:

Student[name=李翔, birthday=2002-10-09, studentId=202019001, school=北京化工大学]
Student[name=汪海, birthday=2002-07-05, studentId=202019012, school=北京化工大学]
Student[name=张凯, birthday=2002-11-23, studentId=202019015, school=北京化工大学]
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

https://blog.csdn.net/hfut_why/article/details/82929206

https://blog.csdn.net/weixin_45503113/article/details/99124988

https://blog.csdn.net/GavinLi2588/article/details/79688452

https://blog.csdn.net/wusunshine/article/details/11917479

https://blog.csdn.net/m0_47384542/article/details/124093498

Java中在数字前自动补零方法_会跑的葫芦怪的博客-CSDN博客_java自动补0

import  java.util.Scanner;
import java.util.Arrays;
public class Main{
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int num=in.nextInt();
        Student[] studentArray = new Student[num];
        for(int i=0;i<num;i++)
        {
            String name=in.next();
            int year=in.nextInt();
            int month=in.nextInt();
            int day=in.nextInt();
            String studentId=in.next();
            String school=in.next();
            studentArray[i]=new Student(name,year,month,day,studentId,school);
        }
        Arrays.sort(studentArray);
        for(Student s:studentArray)
            System.out.println(s);
    }
}
class Student implements Comparable<Student>
{
    private String name,sch,stunum;
    private int year,month,day;

//    @Override
//    public boolean equals
//    {
//
//    }

    Student(String name,int year,int month,int day, String studentId, String school)
    {
        this.name = name;
        this.year = year;
        this.month = month;
        this.day = day;
        this.stunum = studentId;
        this.sch = school;
    }

    @Override
    public int hashCode()
    {
        return 1;
    }

    @Override
    public String toString()
    {
        return ("Student[name="+name+", birthday="+year+"-"+String.format("S02d",month)+"-"+String.format("S02d",day)+", studentId="+stunum+", school="+sch+"]");
    }

    @Override
    public int compareTo(Student s)
    {
        int flag = 0;
        for(int i=0;i<s.stunum.length();i++)
        {
            if(stunum.charAt(i)>s.stunum.charAt(i))
            {
                flag = 1;
                break;
            }
            else if(stunum.charAt(i)<s.stunum.charAt(i))
            {
                flag = -1;
                break;
            }
        }
        return flag == 1 ? 1 : -1;
    }
}

5-6 十六进制数转换为十进制数

输入一个十六进制数转换为十进制数输出。

输入格式:

输入一个十六进制数

输出格式:

输出一个十进制数

输入样例1:

A
 

输出样例1:

10
 

输入样例2:

ffff
 

输出样例2:

65535
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB


import java.util.Scanner;
//进制转换
public class Main {
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        String x = sc.nextLine();
        long a = Long.parseLong(x,16); //16进制转10进制
        System.out.println(a);
    }
}

 7-7 List的使用

本题练习列表的使用。

  • 定义Person类
  1. 定义私有属性String name,int age,使用Eclipse生成每个属性setter 、getter,有参Person(String name,int age) 、无参 构造方法,toString方法。
  • 定义Main类,在main方法中
  1. 定义List list = new ArrayList();
  2. 用键盘给变量n赋值
  3. 生成n个Person对象并添加到列表中,该Person的name和age通过键盘给出
  4. 循环列表,输出列表所有Person对象信息(调用toString方法)
  5. 输入一个字符串表示姓名,判断该字符串表示的Person对象在List中是否存在,如果存在,输出该Person,否则输出此人不存在。

输入格式:

先一行输入n表示对象个数,然后每行输入一个Person对象的name和age
一行输入一个人的姓名对其进行查询

输出格式:

对每一对象,在一行中输出对象的信息。
对查询的人员,查到输出该人的信息,否则输出此人不存在。

输入样例:

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

3
zhang 23
li 44
wang 33
li
 

3
zhang 23
li 44
wang 33
may
 

输出样例:

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

Person [name=zhang, age=23]
Person [name=li, age=44]
Person [name=wang, age=33]
Person [name=li, age=44]
 

Person [name=zhang, age=23]
Person [name=li, age=44]
Person [name=wang, age=33]
此人不存在
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ArrayList<Person>list=new ArrayList<>();
		
		Scanner in=new Scanner(System.in);
		int n=in.nextInt();
		
		for(int i=0;i<n;i++) {
			Person p=new Person(in.next(),in.nextInt());
			list.add(p);
			System.out.println(p.toString());
		}
		String l=in.next();
		int i;
		for(i=0;i<list.size();i++) {
			if(list.get(i).getName().equals(l)) {
				System.out.println(list.get(i).toString());
				break;
			}
				
		}
		if(i==list.size()) {
			System.out.println("此人不存在");
		}
	}

}
class Person{
	private String name;
	private int age;
	
	public Person(String name,int age) {
		this.age=age;
		this.name=name;
	}
	public Person() {
		this.age=age;
		this.name=name;
	}
	
	
	
	@Override
	public String toString() {
		return "Person [name=" + name + ", 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;
	}
	
}

 5-8  jmu-Java-05集合(泛型)-10-GeneralStack

以前定义的IntegerStack接口,只能用于存放Integer类型的数据。然而对于栈来说,不管内部存放的是什么类型的数据,基本操作与元素的具体类型无关。

1. 编写一个通用的GeneralStack接口,接口中的操作对任何引用类型的数据都适用。

一旦定义完毕,只能存放一种类型的数据,比如只能存放String或只能存放Integer。GeneralStack接口方法如下:

push(item);            //如item为null,则不入栈直接返回null。
pop();                 //出栈,如为栈为空,则返回null。
peek();                //获得栈顶元素,如为空,则返回null.
public boolean empty();//如为空返回true
public int size();     //返回栈中元素数量

2.定义GeneralStack的实现类ArrayListGeneralStack

内部使用ArrayList对象存储,属性名为list

方法:
public String toString()//该方法的代码为return list.toString();

提示:

  1. 不用使用top指针。
  2. 直接复用ArrayList中已有的方法。
  3. pop时应将相应的元素从ArrayList中移除。
  4. 代码中不要出现类型不安全的强制转换。

3.定义Car对象

属性:

private int id;
private String name;
 

方法:Eclipse自动生成setter/getter,toString方法。

4.main方法说明

  1. 输入选项,有quit, Integer, Double, Car4个选项。如果输入quit,则直接退出。否则,输入整数m与n。m代表入栈个数,n代表出栈个数。然后声明栈变量stack
  2. 输入Integer,打印Integer Test。建立可以存放Integer类型的ArrayListGeneralStack。入栈m次,出栈n次。打印栈的toString方法。最后将栈中剩余元素出栈并累加输出。
  3. 输入Double ,打印Double Test。剩下的与输入Integer一样。
  4. 输入Car,打印Car Test。其他操作与Integer、Double基本一样。只不过最后将栈中元素出栈,并将其name依次输出。

2、3、4步骤做完都要使用代码System.out.println(stack.getClass().getInterfaces()[0]);打印标识信息

特别注意:如果栈为空的时候继续出栈,则返回null

输入样例

Integer
5
2
1 2 3 4 5
Double
5
3
1.1 2.0 4.9 5.7 7.2
Car
3
2
1 Ford
2 Cherry
3 BYD
quit
 

输出样例

Integer Test
push:1
push:2
push:3
push:4
push:5
pop:5
pop:4
[1, 2, 3]
sum=6
interface GeneralStack
Double Test
push:1.1
push:2.0
push:4.9
push:5.7
push:7.2
pop:7.2
pop:5.7
pop:4.9
[1.1, 2.0]
sum=3.1
interface GeneralStack
Car Test
push:Car [id=1, name=Ford]
push:Car [id=2, name=Cherry]
push:Car [id=3, name=BYD]
pop:Car [id=3, name=BYD]
pop:Car [id=2, name=Cherry]
[Car [id=1, name=Ford]]
Ford
interface GeneralStack
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

import java.util.ArrayList;
import java.util.Scanner;
 
interface GeneralStack<T>{
    public T push(T item);            //如item为null,则不入栈直接返回null。
    public T pop();                 //出栈,如为栈为空,则返回null。
    public T peek();                //获得栈顶元素,如为空,则返回null.
    public boolean empty();//如为空返回true
    public int size();     //返回栈中元素数量
}
class ArrayListGeneralStack implements GeneralStack{
    ArrayList list=new ArrayList();
    @Override
    public String toString() {
        return  list.toString();
    }
 
    @Override
    public Object push(Object item) {
        if (list.add(item)){
            return item;
        }else {
            return false;
        }
    }
 
    @Override
    public Object pop() {
        if (list.size()==0){
            return null;
        }
        return list.remove(list.size()-1);
    }
 
    @Override
    public Object peek() {
        return list.get(list.size()-1);
    }
 
    @Override
    public boolean empty() {
        if (list.size()==0){
            return true;
        }else {
            return false;
        }
    }
 
    @Override
    public int size() {
        return list.size();
    }
}
class Car{
    private int id;
    private String name;
 
    @Override
    public String toString() {
        return "Car [" +
                "id=" + id +
                ", name=" + name  +
                ']';
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Car(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        while (true){
            String s=sc.nextLine();
            if (s.equals("Double")){
                System.out.println("Double Test");
                int count=sc.nextInt();
                int pop_time=sc.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
                for (int i=0;i<count;i++){
                    System.out.println("push:"+arrayListGeneralStack.push(sc.nextDouble()));
                }
                for (int i=0;i<pop_time;i++){
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());
                double sum=0;
                int size=arrayListGeneralStack.size();
                for (int i=0;i<size;i++){
                    sum+=(double)arrayListGeneralStack.pop();
                }
                System.out.println("sum="+sum);
                System.out.println("interface GeneralStack");
            }else if (s.equals("Integer")){
                System.out.println("Integer Test");
                int count=sc.nextInt();
                int pop_time=sc.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
                for (int i=0;i<count;i++){
                    System.out.println("push:"+arrayListGeneralStack.push(sc.nextInt()));
                }
                for (int i=0;i<pop_time;i++){
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());
                int sum=0;
                int size=arrayListGeneralStack.size();
                for (int i=0;i<size;i++){
                    sum+=(int)arrayListGeneralStack.pop();
                }
                System.out.println("sum="+sum);
                System.out.println("interface GeneralStack");
            }else if (s.equals("Car")){
                System.out.println("Car Test");
                int count=sc.nextInt();
                int pop_time=sc.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
                for (int i=0;i<count;i++){
                    int id=sc.nextInt();
                    String name=sc.next();
                    Car car = new Car(id,name);
                    System.out.println("push:"+arrayListGeneralStack.push(car));
                }
                for (int i=0;i<pop_time;i++){
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());
                if (arrayListGeneralStack.size()>0){
                    int size=arrayListGeneralStack.size();
                    for (int i=0;i<size;i++){
                        Car car=(Car) arrayListGeneralStack.pop();
                        System.out.println(car.getName());
                    }
                }
                System.out.println("interface GeneralStack");
            }else if (s.equals("quit")){
                break;
            }
        }
 
    }
}
 

5-9 复制源码

编写程序,将程序文件的源代码复制到程序文件所在目录下的“temp.txt”文件中。

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

5-10 设计一个银行业务类

编写一个银行业务类BankBusiness,具有以下属性和方法:
(1)公有、静态的属性:银行名称bankName,初始值为“中国银行”。
(2)私有属性:账户名name、密码password、账户余额balance。
(3)银行对用户到来的欢迎(welcome)动作(静态、公有方法),显示“中国银行欢迎您的到来!”,其中“中国银行”自动使用bankName的值。
(4)银行对用户离开的提醒(welcomeNext)动作(静态、公有方法),显示“请收好您的证件和物品,欢迎您下次光临!”
(5)带参数的构造方法,完成开户操作。需要账户名name、密码password信息,同时让账户余额为0。
(6)用户的存款(deposit)操作(公有方法,需要密码和交易额信息),密码不对时无法存款且提示“您的密码错误!”;密码正确、完成用户存款操作后,要提示用户的账户余额,例如“您的余额有1000.0元。”。
(7)用户的取款(withdraw)操作(公有方法,需要密码和交易额信息)。密码不对时无法取款且提示“您的密码错误!”;密码正确但余额不足时提示“您的余额不足!”;密码正确且余额充足时扣除交易额并提示用户的账户余额,例如“请取走钞票,您的余额还有500.0元。”。

编写一个测试类Main,在main方法中,先后执行以下操作:
(1)调用BankBusiness类的welcome()方法。
(2)接收键盘输入的用户名、密码信息作为参数,调用BankBusiness类带参数的构造方法,从而创建一个BankBusiness类的对象account。
(3)调用account的存款方法,输入正确的密码,存入若干元。密码及存款金额从键盘输入。
(4)调用account的取款方法,输入错误的密码,试图取款若干元。密码及取款金额从键盘输入。
(5)调用account的取款方法,输入正确的密码,试图取款若干元(取款金额大于余额)。密码及取款金额从键盘输入。
(6)调用account的取款方法,输入正确的密码,试图取款若干元(取款金额小于余额)。密码及取款金额从键盘输入。
(7)调用BankBusiness类的welcomeNext()方法。

输入格式:

输入开户需要的姓名、密码
输入正确密码、存款金额
输入错误密码、取款金额
输入正确密码、大于余额的取款金额
输入正确密码、小于余额的取款金额

输出格式:

中国银行(银行名称)欢迎您的到来!
您的余额有多少元。
您的密码错误!
您的余额不足!
请取走钞票,您的余额还有多少元。
请收好您的证件和物品,欢迎您下次光临!

输入样例:

在这里给出一组输入。请注意,输入与输出是交替的,具体顺序请看测试类中的说明。例如:

张三 123456
123456 1000
654321 2000
123456 2000
123456 500
 

输出样例:

在这里给出相应的输出。请注意,输入与输出是交替的,具体顺序请看测试类中的说明。例如:

中国银行欢迎您的到来!
您的余额有1000.0元。
您的密码错误!
您的余额不足!
请取走钞票,您的余额还有500.0元。
请收好您的证件和物品,欢迎您下次光临!
 

代码长度限制:16 KB

时间限制:400 ms

内存限制:64 MB

import java.util.Scanner;
 
public class Main {
 
	public static void main(String[] args) {
		BankBusiness.welcome();
 
		Scanner in = new Scanner(System.in);
		
		BankBusiness user = new BankBusiness(in.next(), in.next());
		
		user.deposit(in.next(), in.nextDouble());
		user.withdraw(in.next(), in.nextDouble());
		user.withdraw(in.next(), in.nextDouble());
		user.withdraw(in.next(), in.nextDouble());
		BankBusiness.welcomeNext();
	}
 
}
 
class BankBusiness {
 
	public static String bankName = "中国银行";
	private String name,password;
	private double balance;
	
	public static void welcome() {
		System.out.println(bankName+"欢迎您的到来!");
	}
	
	public static void welcomeNext() {
		System.out.println("请收好您的证件和物品,欢迎您下次光临!");
	}
 
	public BankBusiness(String name, String password) {
		super();
		this.name = name;
		this.password = password;
		this.balance = 0;
	}
	
	public void deposit(String password,double change) {
		if(!password.equals(this.password)) {
			System.out.println("您的密码错误!");
			return;
		}
		this.balance += change;
		System.out.println("您的余额有"+this.balance+"元。");
		
	}
	
	public void withdraw(String password,double change) {
		if(!password.equals(this.password)) {
			System.out.println("您的密码错误!");
			return;
		}
		if(this.balance<change) {
			System.out.println("您的余额不足!");
			return;
		}
		this.balance -= change;
		System.out.println("请取走钞票,您的余额还有"+this.balance+"元。");
	}
	
	
}

一、判断题补充

1-1 所谓方法重写,就是在同一个作用域内方法名相同但参数个数或者参数类型不同的方法。

F

1-2 break语句只用于循环语句中,它的作用是跳出循环。

F

还作用于switch语句

1-3 Java语言不区分大小写

F

1-4 Java的Object类没有父类。

T

1-5 在Animal类和其子类Dog类中均定义了一个名为age的整形变量,则按照多态原理,下列程序中访问的是Dog类中的age变量。

Animal a=new Dog();

System.out.println(a.age);

F

多态:调用属性时会向父类索引 父类子类都有有则调用的是父类的属性    父类没有则调用的是子类的属性;调用方法时也是 父类子类都有而且一样的 调用的是父类  子类重写了方法调用的是子类的方法;对于构造方法 在new时候 先调用父类构造方法  不管子类的构造方法是否被super(这个用super调用父类构造器再加子类新属性或者是不加而定义的新构造器不叫重写也不叫重载 就是一个书写子类的通识规范);但是还是先调用父类构造器(???我要是不用super呢?) 再调用子类的构造器 所以父类构造器如果有语句在用new的时候一定会被执行

错题整理1_crystalsugar_的博客-CSDN博客_在animal类和其子类dog类中均定义了一个名为age的整形变量,则按照多态原理,下列程

1-6 使用上转型对象调用子类重写的方法时表现出多态性。

T

Java中什么是上转型对象, 上转型对象如何体现多态?_大图书馆的牧羊人的博客-CSDN博客_上转型对象

对象的上转型对象和多态_I_N_A的博客-CSDN博客_上转型和多态

1-7 可以使用throws语句来指明方法有异常抛出。

T

throw 是语句抛出一个异常;throws 是方法抛出一个异常_Hustudent20080101的博客-CSDN博客_可以使用throws语句来指明方法有异常抛出

1-8 对于泛型类或泛型接口,在编译过程中检查泛型类型的合法性,在对象进入和离开方法的边界处添加类型检查和类型转换的机制,并且泛型信息会保持到运行时阶段。

F

二、单选题补充

2-1 HashSet集合存储下列哪种元素时,要确保不出现重复的元素,必须重写hashcode方法和equals方法()

D.自定义的Student类

2-2 作者 刘凤良 单位 天津仁爱学院

对于break语句和continue语句,说法正确的是( )。

B.continue语句只应用于循环体中

2-3 作者 殷伟凤 单位 浙江传媒学院

Math.floor(3.6)的结果是( )。

C.3.0

floor向下取最大整数

2-4 作者 吕行军 单位 河北农业大学

Java中,Arrays类属于哪个包

C.java.util

2-5 作者 周雪芹 单位 山东理工大学

下面程序的输出结果为:( )。

class A {
 double f(double x, double y) {
  return x * y;
 }
}

class B extends A {
 double f(double x, double y) {
  return x + y;
 }
}

public class Test {
 public static void main(String args[]) {
  A obj = new B();
  System.out.println(obj.f(4, 6));
 }
}

A.10.0

2-6 作者 殷伟凤 单位 浙江传媒学院

可以用于在子类中调用被重写父类方法的关键字是()

D.super

2-7 作者 刘永福 单位 河北农业大学

在Java中,以下()类的对象是以键-值的方式存储对象。

C.HashMap

  • 8
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值