JAVA实验试题

目录

  • ♛系列♕
    • 大王
    • 小王
  • ♠系列♠
    • 黑桃A 重写父类方法
    • 黑桃2 设置点坐标
    • 黑桃3 一年薪水总额
    • 黑桃4 货物的总重量
    • 黑桃5 再加一个冰箱类
    • 黑桃6 继承关系
    • 黑桃7 ArrayList
    • 黑桃8 宠物接口
    • 黑桃9 函数调用
    • 黑桃10 GCD和LCM
    • 黑桃J abstract模拟器
    • 黑桃Q interface模拟器
    • 黑桃K 子类实现面积计算
  • ♥系列♥
    • 红桃A
    • 红桃2
    • 红桃3
    • 红桃4
    • 红桃5
    • 红桃6
    • 红桃7
    • 红桃8
    • 红桃9
    • 红桃10
    • 红桃J 菜单窗体
    • 红桃Q
    • 红桃K
  • ♣系列♣
    • 梅花A 电子邮件的提取
    • 梅花2 字符串回文判断
    • 梅花3 字符串分析器
    • 梅花4 args[ ]的使用
    • 梅花5 大写小写的转换
    • 梅花6 字符串的拼接
    • 梅花7 数组越界处理
    • 梅花8 除以0的处理
    • 梅花9 自定义异常类
    • 梅花10 数字的加密
    • 梅花J 课程平均成绩
    • 梅花Q 数字格式输出
    • 梅花K 提取数字每一位
  • ♦系列♦
    • 方块A 三角形面积和周长
    • 方块2 判断数的符号
    • 方块3 个人所得税
    • 方块4 显示水果的价格
    • 方块5 计算1/(2i-1)前n项和
    • 方块6 序列的奇数和
    • 方块7 位数及数位之和
    • 方块8 素数的判定
    • 方块9 范围内的水仙花数
    • 方块10 整数的逆序
    • 方块J 数组的降序排序
    • 方块Q 统计单词
    • 方块K 字符串的长度

实验考试 同学们,请你们每人抽取1张扑克牌,查看扑克牌代表的题目,认真完成题目。注意:黑桃、红桃以及大小王难度较大,如果感觉完成有困难可重新抽取梅花和方块系列,但是调整一次扣2分。考试时间:30分钟,考试总分为10分

♛系列♕

大王

如下图所示,在处理文本框上出发的ActionEvent事件。在文本框text中输入字符串回车,监视器负责解释字符串的长度,并在命令行窗口显示字符串的长度。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame {
   public Main() {
       Container c = getContentPane();
       c.setLayout(new FlowLayout());
       JTextField jt = new JTextField();
       jt.setColumns(20);
       jt.setFont(new Font("宋体", Font.PLAIN, 20));
       jt.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               jt.getText();
               System.out.println(jt.getText().length());
           }
       });
       c.add(jt);
       setBounds(100, 100, 250, 80);
       setVisible(true);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
   }

   public static void main(String[] args) {
       new Main();
   }
}

小王

创建两个接口,shape,shape3D,接口shape中有计算表面积的getArea()抽象方法,接口shape3D中有计算体积的getVolume()抽象方法,创建长方体类Cuboid和球体类Sphere,这两个类都实现shape,shape3D两个接口。编写类Cuboid和类Sphere的测试程序,并分别计算长方体(长18,宽9,高12)和球体(半径为6)的表面积和体积。

class Main {
    public static void main(String[] args) {
        System.out.println("长方体(长18,宽9,高12)的表面积:" + new Cuboid(18, 9, 12).getArea());
        System.out.println("长方体(长18,宽9,高12)的体积:" + new Cuboid(18, 9, 12).getVolume());
        System.out.println("球体(半径为6)的表面积:" + new Sphere(6).getArea());
        System.out.println("球体(半径为6)的体积:" + new Sphere(6).getVolume());
    }
}

interface shape {
    double getArea();
}

interface shape3D {
    double getVolume();
}

class Cuboid implements shape, shape3D {
    int a, b, c;

    Cuboid(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    @Override
    public double getArea() {
        return 2 * (a * b + a * c + b * c);
    }

    @Override
    public double getVolume() {
        return a * b * c;
    }
}

class Sphere implements shape, shape3D {
    int r;

    Sphere(int r) {
        this.r = r;
    }

    @Override
    public double getArea() {
        return 4 * Math.PI * r * r;
    }

    @Override
    public double getVolume() {
        return 4 * Math.PI * r * r * r / 3;
    }
}

运行结果:
JAVA实验试题_第1张图片

♠系列♠

黑桃A 重写父类方法

编写一个Java应用程序,除了主类外,该程序中还有4个类:People, ChinaPeople,AmericanPeople和BeijingPeople类。要求如下:
1、People类有访问权限是protected的double型成员变量:height和weight,以及public void speakHello()、public void averageHeight()和public void averageWeight()方法。
2、ChinaPeople类是People的子类,新增T public void chinaGongfu()方法。要求ChinaPeople重写父类的public void speakHello(), public void averageHeight()和public void average Weight()方法。
3、AmericanPeople类是People的子类,新增public void americanBoxing()方法。要求AmericanPeople重写父类的public void speakHello( ), public void averageHeight()和public void averageWeight()方法。
4、BeijingPeople类是ChinaPeople的子类,新增public void beijingOpera()方法。要求ChinaPeople重写父类的public void speakHello(), public. void averageHeight()和public void average Weight()方法

class Main {
    public static void main(String[] args) {
        People p = new People();
        ChinaPeople p1 = new ChinaPeople();
        BeijingPeople p2 = new BeijingPeople();
        AmericanPeople p3 = new AmericanPeople();
    }
}

class People {
    protected double heigh;
    protected double weight;

    public void speakHello() {

    }

    public void averageHeight() {

    }

    public void averageWeight() {

    }

}

class ChinaPeople extends People {
    public void chinaGongfu() {

    }

    @Override
    public void speakHello() {
        super.speakHello();
    }

    @Override
    public void averageHeight() {
        super.averageHeight();
    }

    @Override
    public void averageWeight() {
        super.averageWeight();
    }
}

class AmericanPeople extends People {
    public void americanBoxing() {

    }

    @Override
    public void speakHello() {
        super.speakHello();
    }

    @Override
    public void averageHeight() {
        super.averageHeight();
    }

    @Override
    public void averageWeight() {
        super.averageWeight();
    }
}

class BeijingPeople extends ChinaPeople {
    public void beijingOpear() {

    }

    @Override
    public void speakHello() {
        super.speakHello();
    }

    @Override
    public void averageHeight() {
        super.averageHeight();
    }

    @Override
    public void averageWeight() {
        super.averageWeight();  // 此处可以做任意修改,以上需要重写的方法同理.
    }
}

黑桃2 设置点坐标

写出一个Point(点)类,该类具有x,y(表示点的横坐标、纵坐标)两个属性,并定义两个构造方法,第一个构造方法无参数,将x,y均设置为零,第二个构造方法使用坐标值为参数,设置x,y为给定坐标值,同时Point类包含show方法,show方法可以打印输出该类的x和y的值。

public class Main {
   public static void main(String[] args) {
       System.out.println("第一个点为:");
       (new Point()).show();
       System.out.println("第二个点为:");
       (new Point(06, 05)).show();
   }
}

class Point {
   int x, y;

   Point() {
       x = 0;
       y = 0;
   }

   Point(int x, int y) {
       this.x = x;
       this.y = y;
   }

   void show() {
       System.out.println("x = " + x);
       System.out.println("y = " + y);
   }
}

运行结果:
JAVA实验试题_第2张图片

黑桃3 一年薪水总额

要求有一个abstract类,类名为Employee. Employee的子类有YearWorker, MonthWorker和WeekWorkero YearWorke:对象按年领取薪水,MonthWorker按月领取薪水,WeekWorker按周领取薪水。Employee类有一个abstract方法:
public abstract earnings();
子类必须重写父类的earnings()方法,给出各自领取报酬的具体方式。
有一个Company类,该类用Employee数组作为成员,Employee数组的单元可以是YearWorke:对象的上转型对象、MonthWorke:对象的上转型对象或WeekWorker对象的上转型对象。程序能输出Company对象一年需要支付的薪水总额。

import java.nio.file.StandardWatchEventKinds;

// 1年有12个月、1年有48周
class Main {
   public static void main(String[] args) {
       Employee[] e = new Company().emp;
       double sum = 0;
       for (Employee i : e)
           sum += i.earnings();
       System.out.println("该公司一年支付的薪水总额:" + sum);
   }
}

abstract class Employee {
   public abstract double earnings();
}

class YearWorker extends Employee {
   double annual_salary;

   YearWorker(double annual_salary) {
       this.annual_salary = annual_salary;
   }

   public double earnings() {
       return annual_salary;
   }
}

class MonthWorker extends Employee {
   double month_salary;

   MonthWorker(double month_salary) {
       this.month_salary = month_salary;
   }

   public double earnings() {
       return month_salary * 12;
   }
}

class WeekWorker extends Employee {
   double week_salary;

   public WeekWorker(double week_salary) {
       this.week_salary = week_salary;
   }

   public double earnings() {
       return week_salary * 48;
   }
}

class Company {
   public Employee[] emp = {new YearWorker(100000), new MonthWorker(10000), new WeekWorker(3500)};
}

运行结果:
在这里插入图片描述

黑桃4 货物的总重量

卡车要装载一批货物,货物有3种商品:电视、计算机和洗衣机。需要计算出大货车和小货车各自所装载的3种货物的总重量。
要求有一个ComputeWeight接口,该接口中有一个方法:
public double computeWeight()
有3个实现该接口的类:Television, Computer和WashMachine。这3个类通过实现接口computeTotalSales给出自重。
有一个Car类,该类用.ComputeWeight接口类型的数组作为成员,那么该数组的单元,就可以存放Television对象的引用、Computer对象的引用或WashMachine对象的引用。程序能输出Car对象所装载的货物的总重量。

class Main {
   public static void main(String[] args) {
       Car vin = new Car(new ComputeWeight[]{new Television(100), new Computer(200), new WashMachine(300)});
       Car truck = new Car(new ComputeWeight[]{new Television(400), new Computer(500), new WashMachine(600)});
       // 小货车vin  拉电视、计算机、洗衣机的重量依次为:100、200、300;
       // 大货车truck拉电视、计算机、洗衣机的重量依次为:400、500、600;
       double sum = vin.computeTotalSales() + truck.computeTotalSales();

       System.out.println("大小货车装载货物的总重量:" + sum);
   }
}

interface ComputeWeight {
   public double computeWeight();
}

class Television implements ComputeWeight {
   double weight;

   public Television(double weight) {
       this.weight = weight;
   }

   @Override
   public double computeWeight() {
       return weight;
   }
}

class Computer implements ComputeWeight {
   double weight;

   public Computer(double weight) {
       this.weight = weight;
   }

   @Override
   public double computeWeight() {
       return weight;
   }
}

class WashMachine implements ComputeWeight {
   double weight;

   public WashMachine(double weight) {
       this.weight = weight;
   }

   @Override
   public double computeWeight() {
       return weight;
   }
}

class Car {
   ComputeWeight[] computeWeight;

   Car(ComputeWeight[] computeWeight) {
       this.computeWeight = computeWeight;
   }

   double computeTotalSales() {
       double sum = 0;
       for (ComputeWeight i : computeWeight)
           sum += i.computeWeight();
       return sum;
   }
}

运行结果:
在这里插入图片描述

黑桃5 再加一个冰箱类

请在黑桃4的基础上再编写一个实现ComputerWeight接口的类,比如Refrigerrator。这样一来,大货车或小货车装载的货物中就可以有Refrigerrator类型的对象。
增加一个实现ComputerWeight接口的类后,Car类需要进行修改吗?
ans:不需要

class Main {
   public static void main(String[] args) {
       new Car(new ComputeWeight[]{new Refrigerrator()});
   }
}

interface ComputeWeight {
   public double computeWeight();
}

class Television implements ComputeWeight {
   double weight;

   public Television(double weight) {
       this.weight = weight;
   }

   @Override
   public double computeWeight() {
       return weight;
   }
}

class Computer implements ComputeWeight {
   double weight;

   public Computer(double weight) {
       this.weight = weight;
   }

   @Override
   public double computeWeight() {
       return weight;
   }
}

class WashMachine implements ComputeWeight {
   double weight;

   public WashMachine(double weight) {
       this.weight = weight;
   }

   @Override
   public double computeWeight() {
       return weight;
   }
}

class Car {
   ComputeWeight[] computeWeight;

   Car(ComputeWeight[] computeWeight) {
       this.computeWeight = computeWeight;
   }

   double computeTotalSales() {
       double sum = 0;
       for (ComputeWeight i : computeWeight)
           sum += i.computeWeight();
       return sum;
   }
}

class Refrigerrator implements ComputeWeight {
   @Override
   public double computeWeight() {
       return 0;
   }
}

黑桃6 继承关系

利用继承关系,设计名为Person、Student、Teacher三个类,其中Person有姓名和年龄属性;Student有班级状态属性(一年级、二年级等),有上学的行为;Teacher有办公室和工资的属性,有授课的行为。Teacher和Student覆盖Person类中的toString方法,显示各自的类型信息,同时注意这三个类中的数据的封装(信息的隐藏)。

public class Main {
   public static void main(String[] args) {
       Student stu = new Student();
       Teacher tea = new Teacher();
       // 测试Student类
       System.out.println(stu.toString());
       stu.setName("Leibniz");
       stu.setAge(23);
       stu.setGrade(2);
       System.out.println("name: " + stu.getName());
       System.out.println("age: " + stu.getAge());
       System.out.println("class: " + stu.getGrade());
       stu.study();
       System.out.println("---------------");
       // 测试Teacher类
       System.out.println(tea.toString());
       tea.setName("Taylor");
       tea.setAge(36);
       tea.setOffice("1D-403");
       tea.setSalary(7799);
       System.out.println("name: " + tea.getName());
       System.out.println("age: " + tea.getAge());
       System.out.println("office: " + tea.getOffice());
       System.out.println("salary: " + tea.getSalary());
       tea.teaching();
   }
}

class Person {
   private String name;
   private int 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;
   }
}

class Student extends Person {
   private int grade;

   @Override
   public String toString() {
       return "我是student";
   }

   // 自定义方法
   void study() {
       System.out.println("I am learning.");
   }

   public int getGrade() {
       return grade;
   }

   public void setGrade(int grade) {
       this.grade = grade;
   }
}

class Teacher extends Person {
   private String office;
   private int salary;

   @Override
   public String toString() {
       return "我是teacher";
   }

   // 自定义方法
   void teaching() {
       System.out.println("I am teaching.");
   }

   public String getOffice() {
       return office;
   }

   public void setOffice(String office) {
       this.office = office;
   }

   public int getSalary() {
       return salary;
   }

   public void setSalary(int salary) {
       this.salary = salary;
   }
}

运行结果:
JAVA实验试题_第3张图片

黑桃7 ArrayList

利用继承关系,设计名为Person、小学生PupilStudent、研究生GraduateStudent三个类,其中每个类都有toString方法返回各自的类型信息。PupilStudent有上学方法GoToSchool,GraduateStudent有从事项目方法DoProject;根据多态性,使用ArrayList链表将各个对象放入其中。利用循环取出链表中的元素,根据类型调用相应的方法。最后清空链表中的元素。

import java.util.ArrayList;

public class Main {
   public static void main(String[] args) {
       ArrayList<Person> list = new ArrayList();
       Person person = new Person();
       PupilStudent pupil = new PupilStudent();
       GraduateStudent graduate = new GraduateStudent();
       list.add(person);
       list.add(pupil);
       list.add(graduate);
       while (!list.isEmpty()) {
           System.out.println(list.get(0).toString());
           list.remove(0);
       }
   }
}

class Person {
}

class PupilStudent extends Person {
   void GoToSchool() {
   }
}

class GraduateStudent extends Person {
   void GraduateStudent() {
   }
}

黑桃8 宠物接口

设计一个接口实现照顾宠物的行为,名为TakeCareOfPets,该接口描述了喂食feed、和它完play两个行为。设计三个类,学生、教授和校长,分别实现该接口。

public class Main {
   public static void main(String[] args) {
       
   }
}

interface TakeCareOfPets {
   void feed();

   void play();
}

class Student implements TakeCareOfPets {
   public void feed() {
   }

   public void play() {
   }
}

class Professial implements TakeCareOfPets {
   public void feed() {
   }

   public void play() {
   }
}

class Master implements TakeCareOfPets {
   public void feed() {
   }

   public void play() {
   }
}

黑桃9 函数调用

编写一个类A,该类创建的对象可以调用方法f输出英文字母表,然后再编写一个该类的子类,要求子类必须继承A类的方法f(不允许重写),子类创建的对象不仅可以调用方法f输出英文字母表而且调用子类新增的方法g输出希腊字母表。

public class Main {
   public static void main(String[] args) {
       B obj = new B();
       obj.f();
       System.out.println();
       obj.g();
   }
}

class A {
   void f() {
       for (char t = 'a'; t <= 'z'; t++) {
           System.out.print(t);
       }
   }
}

class B extends A {
   void g() {
       for (char t = 'α'; t <= 'ω'; t++) {
           System.out.print(t);
       }
   }
}

运行结果:
在这里插入图片描述

黑桃10 GCD和LCM

编写一个类,该类有一个方法public int f(int a,int b),该方法返回a和b 的最大公约数,然后再编写一个该类的子类,要求子类重写方法f,而且重写的方法将返回a和b的最小公倍数要求在重写的方法的方法体中首先调用被隐藏的方法返回a和b的最大公约数m,然后再将成绩(a*b)/m返回,要求在应用程序的主类中分别使用父类和子类创建对象,别分别调用方法f计算两个正整数的最大公约数和最小公倍数。

正解代码:

public class Main {
   public static void main(String[] args) {
       System.out.println((new GCD()).f(9, 12));
       System.out.println((new LCM()).f(9, 12));
   }
}

class GCD {
   public int f(int a, int b) {
       return b != 0 ? f(b, a % b) : a;
   }
}

class LCM extends GCD {
   public int f(int a, int b) {
       return a * b / new GCD().f(a, b);
   }
}

错误代码:

public class Main {
    public static void main(String[] args) {
        System.out.println((new GCD()).f(9, 12));
        System.out.println((new LCM()).f(9, 12));
    }
}

class GCD {
    public int f(int a, int b) {
        return b != 0 ? f(b, a % b) : a;
    }
}

class LCM extends GCD {
    public int f(int a, int b) {
        return a * b / super.f(a, b);
        // 只会调用一次父类中被重写的方法;
        // 即:第1次调用的super.f();
        // 而第二次的f()是属于子类的.
    }
}

黑桃J abstract模拟器

设计一个动物声音“模拟器“,希望没几起可以模拟许多动物的叫声,要求如下。
1、编写抽象类Animal
Animal抽象类有两个抽象方法cry()和getAnimalName(),即要求各种具体的动物给出自己的叫声和种类名称。
2、编写模拟器类Simulator
该类有一个playSound(Animal animal)方法,该方法的参数是Animal类型。即参数animal可以调用Animal的子类重写cry()方法包房具体的动物的声音,调用子类重写的getAnimalName()方法显示动物种类的名称。
3、编写Animal类的子类:Dog和Cat类。
4、编写主类,主类中至少包含如下代码:
Simulator simulator = new Simulator();
Simulator.playSound(new Dog());
Simulator.playSound(new Cat());

public class Main {
   public static void main(String[] args) {
       Simulator simulator = new Simulator();

       simulator.playSound(new Dog());
       simulator.playSound(new Cat());
       simulator.getAnimalName(new Dog());
       simulator.getAnimalName(new Cat());
   }
}

abstract class Animal {
   abstract void cry();

   abstract void getAnimalName();
}

class Simulator {
   void playSound(Animal animal) {
       animal.cry();
   }

   void getAnimalName(Animal animal) {
       animal.getAnimalName();
   }
}

class Dog extends Animal {
   void cry() {
       System.out.println("狗在叫!");
   }

   void getAnimalName() {
       System.out.println("这是狗!");
   }
}

class Cat extends Animal {
   void cry() {
       System.out.println("猫在叫!");
   }

   void getAnimalName() {
       System.out.println("这是猫!");
   }
}

黑桃Q interface模拟器

和黑桃J个题目类似,不过这里要求使用接口。要求如下:
1、把Animal编写为接口,包含cry()和getAnimalName()两个抽象方法。
2、编写模拟器类Simulator
该类有一个playSound(Animal animal)方法,该方法的参数是Animal类型。即参数animal可以调用Animal的子类重写cry()方法包房具体的动物的声音,调用子类重写的getAnimalName()方法显示动物种类的名称。
3、编写应用Animal接口的子类:Dog和Cat类。
4、别写主类,主类中至少包含如下代码:
Simulator simulator = new Simulator();
Simulator.playSound(new Dog());
Simulator.playSound(new Cat());

public class Main {
   public static void main(String[] args) {
       Simulator simulator = new Simulator();

       simulator.playSound(new Dog());
       simulator.playSound(new Cat());
       simulator.getAnimalName(new Dog());
       simulator.getAnimalName(new Cat());
   }
}

interface Animal {
   void cry();

   void getAnimalName();
}

class Simulator {
   void playSound(Animal animal) {
       animal.cry();
   }

   void getAnimalName(Animal animal) {
       animal.getAnimalName();
   }
}

class Dog implements Animal {
   public void cry() {
       System.out.println("狗在叫!");
   }

   public void getAnimalName() {
       System.out.println("这是狗!");
   }
}

class Cat implements Animal {
   public void cry() {
       System.out.println("猫在叫!");
   }

   public void getAnimalName() {
       System.out.println("这是猫!");
   }
}

黑桃K 子类实现面积计算

编写一个应用程序,要求定义一个抽象的父类shape,在父类中要求包含抽象方法area()。再定义个子类circle,继承shape类,并实现从键盘输入一个double型的圆的半径,计算并输出其面积。

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
       System.out.println("area = " + new circle().area());
   }
}

abstract class shape {
   abstract double area();
}

class circle extends shape {
   public double area() {
       Scanner cin = new Scanner(System.in);
       double radius = cin.nextDouble();
       return radius * radius * Math.PI;
   }
}

♥系列♥

红桃A

编写一个应用程序,有一个标题为“挑单词”的窗口,窗口的布局为BorderLayout布局。窗口中添加两个文本区和一个按钮组件,要求文本区分别添加到窗口的东部和西部;按钮添加到窗口的那不,当单击按钮式,程序将东部的文本区鼠标选中的内容为添加到西部区域的文本区中。(注:本区可以使用getSelectedText()方法获取爱问不去通过拖动鼠标选中的文本。)

红桃2

编写一个应用程序,要求有一个画布,在画布上绘制一个矩形,用户通过文本框数据如矩形的宽和高以及矩形的左上角的位置坐标。

红桃3

编写一个应用程序,要求编写一个Panel的子类MyPanel中有一个文本框和一个按钮,要求MyPanel的实例作为其按钮的ActionEvent事件的监视器,当打击按钮时,程序获取文本框中的文本,并将该文本作为按钮的名称,然后再白那些一个Frame的子类,窗口使用其默认布局。窗口中添加两个MyPanel面板,分别添加到窗口的东部和西部。

红桃4

编写一个应用程序,有一个标题为“改变颜色”的窗口,窗口的布局为null,在窗口中有3个按钮和一个画布,3个按钮的颜色分别是红、绿、蓝。单击相应的按钮,换不绘制对应的颜色的圆。

红桃5

编写应用程序,有一个标题为“计算“的窗口,窗口的布局范围FlowLayout布局。窗口中添加两个文本区,当我们在一个文本区中输入若干个数十,另一个文本区同时对你输入的数进行求和运算并求出平均值,也就是说随着你输入的变化,另一个文本区不断地更新求和及平均值。

红桃6

编写一个应用程序,有一个标题为“计算“的窗口,窗口的布局为FlowLayout布局。设计4个按钮,分别命名为“加”、“差”、“积”、“除”,另外,窗口中还有3个文本框。单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。要求处理NumberFormatException异常。

红桃7

猜数字游戏,要求程序中要有2个按钮buttonGetNumber和buttonNumber,用户单击buttonGetNumber 按钮可以得到一个随机数,然后在文本框中输入猜测数字,再单击buttonNumber按钮,程序根据用户的猜测给出提示信息。 运行效果示例:

红桃8

布局和日历。
利用Swing编写一个GUI程序,JFrame使用BorderLayout布局。在JFrame的中心添加一个Panel容器pCenter, pCenter的布局是7行7列的GridLayout布局,pCenter中放置49个标签,用来显示日历。JFrame的北面添加一个Panel容器pNorth,其布局是FlowLayout布局,pNorth放置两个按钮nextMonth和previousMonth,单击nextMonth按钮,可以显示当前月的下一月的日历;单击previousMonth按钮,可以显示当前月的上一月的日历。JFrame的南面添加一个Panel容器pSouth,其布局也是FlowLayout,pSouth中放置一个标签来显示一些日历信息。运行效果示例:

红桃9

编写一个应用程序,有个标题为“移动”的窗口,窗口的布局为null,在窗口中有两个按钮,单击一个按钮让另一个按钮移动。

红桃10

编写一个应用程序,用户可以在一个文本框中输入数字字符,按Enter键后将数字放入一个文本区。当输入的数字大于1000时,弹出一个有模式的对话框,提示用户数字已经大于1000,是否继续将该数字放入文本区。

红桃J 菜单窗体

在主类的main方法中用Jframe的子类创建一个含有菜单的窗口,效果如下图:
待完善

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main extends JFrame implements ActionListener {
    JLabel label = new JLabel("请选择菜单", JLabel.CENTER);
    JMenuItem aaMenuItem;
    JMenuItem baMenuItem;

    Main() {
        JMenuBar menuBar = new JMenuBar();
        JMenu aMenu = new JMenu("菜单A");
        JMenu bMenu = new JMenu("菜单B");
        JMenuItem aaMenuItem = new JMenuItem("Java话题");
        JMenuItem abMenuItem = new JMenuItem("动画话题");
        JMenuItem baMenuItem = new JMenuItem("软件项目");
        menuBar.add(aMenu);
        menuBar.add(bMenu);
        aMenu.add(aaMenuItem);
        aMenu.addSeparator();
        aMenu.add(abMenuItem);
        bMenu.add(baMenuItem);
        aaMenuItem.addActionListener(this);
        abMenuItem.addActionListener(this);
        baMenuItem.addActionListener(this);
        setJMenuBar(menuBar);
        getContentPane().add(label, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {
        JMenuItem source = (JMenuItem) (e.getSource());
        label.setText("选择了菜单:" + source.getText());
        label.setHorizontalAlignment(JLabel.CENTER);
    }

    public static void main(String[] args) {
        JFrame frame = new Main();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}

JAVA实验试题_第4张图片

红桃Q

编写一个程序,要求包含 JtextField、JtextArea、JButton、JLabel、JCheckBOX、JRadioButton、JComboBox、和JpasswordField,效果如下图:

红桃K

在窗口的中心位置添加了一个选项卡窗格,该选项卡窗格里添加了一个网格布局面板和一个空布局的面板。效果如下图:

♣系列♣

梅花A 电子邮件的提取

在一个字符串中提取出电子邮件的账号。已知条件:该字符串中邮件账号前是一个空格,账号后是一个叹号。该字符串中只有一个邮件账号,也只有一个叹号。

class Main {
   public static void main(String[] arr) {
       String email = "adc def [email protected]! gh";
       for (int i = 0; i < email.length(); i++) {
           if (email.charAt(i) == ' ') {
               int j = i;
               while (j < email.length() && email.charAt(j) != '!') j++;

               // 穷举 以空格开头,叹号结束的所有字符串 判断其内部是否有空格;
               // 若有,则当前字符串不满足要求;
               boolean flag = false;
               for (int k = i + 1; k < j; k++)
                   if (email.charAt(k) == ' ') flag = true;
               if (flag) continue;

               if (j < email.length() && email.charAt(j) == '!')
                   for (int k = i + 1; k < j; k++)
                       System.out.print(email.charAt(k));
           }
       }
   }
}

梅花2 字符串回文判断

从控制台输入一个字符串,判断其是不是回文字符串(即翻转前和翻转后是否相同)。

import java.util.Scanner;

class Main {
   public static void main(String[] arr) {
       Scanner cin = new Scanner(System.in);
       String s = cin.next();
       for (int i = 0, j = s.length() - 1; i < j; i++, j--)
           if (s.charAt(i) != s.charAt(j)) {
               System.out.println("NO");
               return;
           }
       System.out.println("YES");
   }
}

梅花3 字符串分析器

使用字符串分析器StringTokenizer分析字符串,输出单词的总数和每个单词。

import java.util.StringTokenizer;

public class Main {
   public static void main(String[] args) {
       String str = "June July August September October";
       StringTokenizer stk = new StringTokenizer(str, " ");
       int cnt=0;
       while (stk.hasMoreTokens()) {
           System.out.println(stk.nextToken());
           cnt++;
       }
       System.out.println("The number of words is "+cnt+'.');
   }
}

梅花4 args[ ]的使用

编写程序,在命令行输入“java data 11 24 62 73 103 56”,求这一串数字的最大值和平均数。

class data{
   public static void main(String[] arr) {
       int max = Integer.MIN_VALUE, sum = 0;
       for (String t : arr) {
           int x = Integer.parseInt(t);
           if (x > max) max = x;
           sum += x;
       }
       System.out.println("max=" + max + " average=" + 1.0 * sum / arr.length);
   }
}

运行结果:
JAVA实验试题_第5张图片

梅花5 大写小写的转换

使用String类的public String to UpperCase()方法和public String to LowerCase()方法实现字符串中大小写字母的转化,编写程序并实现。

class Main {
   public static void main(String[] arr) {
       String s = "abcdefg";
       String t1 = s.toUpperCase();
       String t2 = t1.toLowerCase();
       System.out.println(t1);
       System.out.println(t2);
   }
}

梅花6 字符串的拼接

使用String类的public String concat(String str)方法可以把调用该方法的字符串与参数指定的字符串连接,把str指定的串连接到当前串的尾部获得一个新的串。编写一个程序通过连接两个串得到一个新的串,并输出这个新串。

import java.util.Scanner;

class Main {
   public static void main(String[] arr) {
       Scanner cin = new Scanner(System.in);
       String s1 = cin.next();
       String s2 = cin.next();
       String res = s1.concat(s2);
       System.out.println(res);
   }
}

梅花7 数组越界处理

程序编写过程中,遇到数组越界时,可以使用异常处理。

class Main {
    public static void main(String[] arr) {
        int[] g = {1, 2, 3};
        try {
            for (int i = 0; i < 4; i++)
                System.out.println(g[i]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Incorrect array Bounds!");
        }
    }
}

梅花8 除以0的处理

程序编写过程中,遇到除法为零时,可以使用异常处理。

class Main {
   public static void main(String[] arr) {
       try {
           int x = 100 / 0;
           System.out.println("我想被执行");
       } catch (ArithmeticException e) {
           System.out.println("除数为零,引发算术异常!");
       }
   }
}

梅花9 自定义异常类

自定义一个年龄异常类,主程序中接受控制台的输入作为年龄的值。使用自定义的异常类进行处理,如果该值为负数,提示年龄不能为负数。如果该值大于200,提示年龄过大。

import java.util.Scanner;

class AgeException extends Exception {
   public AgeException() {
   }

   public AgeException(String message) {
       super(message);
   }
}

public class Main {
   public static void main(String[] args) {
       System.out.println("Enter your age:");
       Scanner scanner = new Scanner(System.in);
       int age = scanner.nextInt();
       if (checkAge(age)) System.out.println("age is valid");
   }
   
   public static boolean checkAge(int age) {
       try {
           if (age < 0) throw new AgeException("age is negative!");
           else if (age > 200) throw new AgeException("age is bigger!");
       } catch (AgeException e) {
           System.out.println(e);
       }
       return true;
   }
}

梅花10 数字的加密

数字加密。输入1个四位数,将其加密后输出。方法是将该数每一位上的数字加9,然后除以10取余,做为该位上的新数字,最后将第1位和第3位上的数字互换,第2位和第4位上的数字互换,组成加密后的新数。

import java.util.Scanner;

class Main {
   public static void main(String[] args) {
       Scanner cin = new Scanner(System.in);
       String num = cin.next();
       String ans = encryption(num);
       System.out.println(ans);
   }

   public static String encryption(String str) {
       // 字符串暂时转成字符数组,方便处理
       char[] s = str.toCharArray();
       for (int i = 0; i < str.length(); i++) {
           int t = s[i] - '0';
           t = (t + 9) % 10;
           s[i] = (char) ('0' + t);
       }
       for (int i = 0; i < 2; i++) {
           char t = s[i];
           s[i] = s[i + 2];
           s[i + 2] = t;
       }
       // 将处理完后的字符数组以字符串的形式返回
       return new String(s);
   }
}

梅花J 课程平均成绩

计算三门课程的平均成绩。已知某位学生的数学、英语和计算机课程的成绩分别是87分、72分和93分,求该生3门课程的平均分。(不限方法)

class Main {
   public static void main(String[] args) {
       int[] score = {87, 72, 93};
       int sum = 0;
       for (int i : score) sum += i;
       System.out.println(sum / 3.0);
   }
}

梅花Q 数字格式输出

计算存款利息。输入存款金额、存期 year 和年利率 rate,根据下列公式计算存款到期时的利息 interest,输出时保留2位小数。
公式:interest = money(1+rate)*year – money

import java.text.DecimalFormat;
import java.util.Scanner;

class Main {
   public static void main(String[] args) {
       Scanner cin = new Scanner(System.in);
       int money = cin.nextInt();
       int year = cin.nextInt();
       double rate = cin.nextDouble();
       double interst = money * (1 + rate) * year - money;
       System.out.println(String.format("%.2f", interst));
   }
} // 格式的输出有以下两个简单形式↓

System.out.println((new DecimalFormat("#.00")).format(12.3456));
System.out.println(String.format("%.2f", 12.3456));

梅花K 提取数字每一位

计算一个3位数的各位数字。
输入一个3位数n,分别求出 n 的个位数字( c )、十位数字( b )和百位数字( a )的值。

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int x = cin.nextInt();
        while (x > 0) {
            System.out.println(x % 10);
            x /= 10;
        }
    }
}

♦系列♦

方块A 三角形面积和周长

求三角形的面积和周长.输入一个正整数repeat (0 输入三角形的三条边a, b, c,如果能构成一个三角形,输出面积area和周长perimeter;否则,输出“These sides do not correspond to a valid triangle”。
注意:在一个三角形中,任意两边之和大于第三边,需要判断。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int repeat = cin.nextInt();
        while (repeat-- > 0) {
            double a = cin.nextDouble();
            double b = cin.nextDouble();
            double c = cin.nextDouble();
            if (a + b > c && a + c > b && b + c > a) {
                double perimeter = a + b + c;
                double p = perimeter / 2;
                double area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
                System.out.println("Area=" + area + " Perimeter=" + perimeter);
            } else {
                System.out.println("These sides do not correspond to a valid triangle");
            }
        }
    }
}

方块2 判断数的符号

判断数的符号。输入整数x,若x大于0,y=1;若x等于0,y=0;否则,y=-1,最后输出y。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int x = cin.nextInt(), y;
        if (x > 0) y = 1;
        else if (x == 0) y = 0;
        else y = -1;
        System.out.println(y);
    }
}

方块3 个人所得税

计算个人所得税。输入一个正整数repeat (0 输入一个职工的月薪salary,输出应交的个人所得税tax。
tax = rate * (salary-850)
当 salary <= 850 时,rate = 0%;
当 850 < salary <= 1350 时,rate = 5%;
当 1350 < salary <= 2850 时,rate = 10%;
当 2850 < salary <= 5850 时,rate = 15%;
当 5850 < salary 时,rate = 20%;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int repeat = cin.nextInt(), salary;
        double tax, rate;
        while (repeat-- > 0) {
            salary = cin.nextInt();
            if (salary > 5850) rate = 0.2;
            else if (salary > 2850) rate = 0.15;
            else if (salary > 1350) rate = 0.1;
            else if (salary > 850) rate = 0.05;
            else rate = 0;
            tax = rate * (salary - 850);
            System.out.println(tax);
        }
    }
}

方块4 显示水果的价格

显示水果的价格。输入一个正整数repeat (0 以下4种水果的单价分别是3.00元/公斤,2.50元/公斤,4.10元/公斤,10.20元/公斤。
[1] apples [2] pears [3] oranges [4] grapes
输入水果的编号,输出该水果的单价。如果输入不正确的编号,显示单价为0。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int repeat = cin.nextInt(), num;
        while (repeat-- > 0) {
            num = cin.nextInt();
            if (num == 1) System.out.println(3.00);
            else if (num == 2) System.out.println(2.50);
            else if (num == 3) System.out.println(4.10);
            else if (num == 4) System.out.println(10.20);
            else System.out.println(0);
        }
    }
}

方块5 计算1/(2i-1)前n项和

求1+1/3+1/5+1/7+……。输入一个正整数repeat (0

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int repeat = cin.nextInt();
        while (repeat-- > 0) {
            int n = cin.nextInt();
            double sum = 0;
            for (int i = 1; i <= n; i++) {
                sum += 1.0 / (2 * i - 1);
            }
            System.out.println(sum);
        }
    }
}

方块6 序列的奇数和

求奇数和。输入一个正整数repeat (0 读入一批正整数(以零或负数为结束标志),求其中的奇数和。注意:需要用到continue。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int repeat = cin.nextInt();
        while (repeat-- > 0) {
            int x, sum = 0;
            do {
                x = cin.nextInt();
                if (x <= 0 || x % 2 == 0) continue;
                sum += x;
            } while (x > 0);
            System.out.println(sum);
        }
    }
}

方块7 位数及数位之和

求整数的位数以及各位数之和。输入一个正整数repeat (0

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int repeat = cin.nextInt();
        while (repeat-- > 0) {
            int x = cin.nextInt(), len = 0, sum = 0;
            while (x > 0) {
                sum += x % 10;
                len++;
                x /= 10;
            }
            System.out.println("length:" + len + " Sum=" + sum);
        }
    }
}

方块8 素数的判定

判断素数。输入一个正整数repeat (0 输入一个正整数m,如果它是素数,输出"YES",否则,输出"NO"(素数就是只能被1和自身整除的正整数,1不是素数,2是素数)。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int repeat = cin.nextInt();
        while (repeat-- > 0) {
             int m = cin.nextInt();
             if (is_prime(m)) System.out.println("YES");
            else System.out.println("NO");
        }
    }

    private static boolean is_prime(int x) {
        if (x < 2) return false;
        for (int i = 2; i <= x / i; i++)
            if (x % i == 0)
                return false;
        return true;
    }
}

方块9 范围内的水仙花数

求各位数字的立方和等于它本身的数。输入2 个正整数m和n(1<=m,n<=1000),输出m 和n之间所有满足各位数字的立方和等于它本身的数。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int m = cin.nextInt();
        int n = cin.nextInt();
        if (m > n) {
            int t = m;
            m = n;
            n = t;
        }
        for (int i = m; i <= n; i++)
            if (value(i) == i)
                System.out.println(i);
    }

    private static int value(int x) {
        int res = 0;
        while (x > 0) {
            res += (x % 10) * (x % 10) * (x % 10);
            x /= 10;
        }
        return res;
    }
}

方块10 整数的逆序

将一个整数逆序输出。(不限方法)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int x=cin.nextInt();
        if(x>0) {
            while (x > 0) {
                System.out.print(x % 10);
                x /= 10;
            }
        }else{
            System.out.print('-');
            x=-x;
            while (x > 0) {
                System.out.print(x % 10);
                x /= 10;
            }
        }
    }
}

方块J 数组的降序排序

排序。输入n个整数,将它们从大到小排序后输出。

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        final int N = 1010;
        int[] a = new int[N];
        int n = cin.nextInt();
        for (int i = 0; i < n; i++) a[i] = cin.nextInt();
        Arrays.sort(a, 0, n);
        for (int i = 0, j = n - 1; i < j; i++, j--) {
            int t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
        for (int i = 0; i < n; i++) System.out.print(Integer.toString(a[i]) + ' ');
    }
}

或者

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = cin.nextInt();
        Arrays.sort(a);
        for (int i = 0, j = n - 1; i < j; i++, j--) {
            int t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
        for (int i : a) System.out.print(Integer.toString(i) + ' ');
    }
}

方块Q 统计单词

统计单词。输入一行字符,统计其中单词的个数。各单词之间用空格分隔,空格数可以是多个。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        String str = cin.nextLine();
        int cnt = 0;
        for (int i = 0; i < str.length(); i++) {
            int j = i;
            if (str.charAt(i) == ' ') continue;
            while (j + 1 < str.length() && str.charAt(j + 1) != ' ') j++;
            cnt++;
            i = j;
        }
        System.out.println(cnt);
    }
}

方块K 字符串的长度

求字符串长度.输入一行以 # 结束的多串字符(不包含空格,各串之间也用 # 进行间隔)。统计并输出每串字符的长度。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        String str = "";
        do {
            str = cin.next();
            System.out.println("Length of \"" + str + "\" is " + str.length() + '.');
        } while (str.charAt(str.length() - 1) != '#');
    }
}

你可能感兴趣的:(java,开发语言)