Java常见练手程序《“书写”百遍,其义自见》

 1、锻炼重写方法、抽象类定义、常量、自定义异常与调用。

  •  建立一个Java抽象类Drink,应当

    a、声明一个抽象方法taste() 该方法负责输出饮料的味道
    b、声明int型常量来代表不同的饮料类型 咖啡、啤酒、牛奶
    c、声明静态方法getDrink(int drinkType) 根据传入的参数创建不同的饮料对象 并返回该对象 建议使用switch语句。该方法要求声明DrinkNotFoundException 当没有相对应的饮料类型时 抛出该异常。

  •  建立Drink的具体子类

    a、分别建立Drink的子类 Coffee 代表咖啡 Beer 代表啤酒 Milk 代表牛奶 ;
    b、实现taste()方法 要求在控制台打印各自的味道特征。
    建立Test测试类 测试以上内容的正确性
    a、编写main方法 通过命令行传参的方式传入某种饮料的类型。
    b、在main方法中 调用Drink类的getDrink方法 获得相应的饮料对象。注意捕获DrinkNotFoundException。
    c、然后调用该饮料对象的taste()方法 输出该饮料的味道。
    编译程序 并运行。

  • Drink类

public abstract class Drink {

    public abstract void taste();

    private static final int COFFEE=1;
    private static final int BEER=2;
    private static final int MILK=3;

    public static Drink getDrink(int drinkType) throws DrinkNotFoundException{
        switch(drinkType){
            case COFFEE:
                return new Coffee();
            case BEER:
                return new Beer();
            case MILK:
                return new Milk();
            default:
                throw new DrinkNotFoundException("Invalid drink type");
        }
    }
}

DrinkNotFoundException(自定义异常类)

public class DrinkNotFoundException extends Exception {
    public DrinkNotFoundException(String message) {
        super(message);
    }
}

Coffee类

public class Coffee extends Drink {
    @Override
    public void taste() {
        System.out.println("咖啡的味道:苦涩");
    }
}

Beer类

public class Beer extends Drink {
    @Override
    public void taste() {
        System.out.println("啤酒的味道:苦中带甜");
    }
}

Milk类

public class Milk extends Drink {
    @Override
    public void taste() {
        System.out.println("牛奶的味道:甜而清香");
    }
}

测试类

public class Test {
    public static void main(String[] args) {
        System.out.println("数字:");
        Scanner scanner=new Scanner(System.in);
        try {
            int drinkType=scanner.nextInt();
            Drink drink = Drink.getDrink(drinkType);
            drink.taste();
        } catch (DrinkNotFoundException e) {
            System.out.println("没有相应的饮料类型");
        }
    }
}

 2、定义复数的类Complex并测试其功能。
    

    14.1. 复数由实部、虚部两个部分组成,在类的定义中应包含保存这两部分信息的内容。

    14.2. 在类中定义构造函数,使用户能够在构造对象的同时为对象赋初值。

    14.3. 在类中定义复数的加法、减法、乘法三个二元操作符来完成复数间的加、减、乘的功能。
    14.4. 通过重载toString,使得Complex类的对象能够显示其自身信息。  

    14.5. 通过显示定义一个成员函数完成对象的赋值操作,使用户能够对Complex类的对象进行赋值。

    14.6. 编写一段主程序(main函数),使用户能够通过这段主程序输入复数并进行复数的计算。

Complex类

public class Complex {
    private double real;
    private double imaginary;

    public Complex(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }
    
    public Complex add(Complex c) {
        double realSum = this.real + c.real;
        double imaginarySum = this.imaginary + c.imaginary;
        return new Complex(realSum, imaginarySum);
    }
    
    public Complex subtract(Complex c) {
        double realDiff = this.real - c.real;
        double imaginaryDiff = this.imaginary - c.imaginary;
        return new Complex(realDiff, imaginaryDiff);
    }
    
    public Complex multiply(Complex c) {
        double realProduct = this.real * c.real - this.imaginary * c.imaginary;
        double imaginaryProduct = this.real * c.imaginary + this.imaginary * c.real;
        return new Complex(realProduct, imaginaryProduct);
    }
    
    public void assign(Complex c) {
        this.real = c.real;
        this.imaginary = c.imaginary;
    }
    
    @Override
    public String toString() {
        return real + " + " + imaginary + "i";
    }
}

Main类

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("请输入第一个复数的实部:");
        double real1 = scanner.nextDouble();
        System.out.println("请输入第一个复数的虚部:");
        double imaginary1 = scanner.nextDouble();
        Complex complex1 = new Complex(real1, imaginary1);
        
        System.out.println("请输入第二个复数的实部:");
        double real2 = scanner.nextDouble();
        System.out.println("请输入第二个复数的虚部:");
        double imaginary2 = scanner.nextDouble();
        Complex complex2 = new Complex(real2, imaginary2);
        
        Complex sum = complex1.add(complex2);
        Complex difference = complex1.subtract(complex2);
        Complex product = complex1.multiply(complex2);
        
        System.out.println("两个复数的和为:" + sum);
        System.out.println("两个复数的差为:" + difference);
        System.out.println("两个复数的积为:" + product);
        
        scanner.close();
    }
}

3、将字符串解析,按照总成绩排序显示学生的信息。


    "张三,语文89,英语75#李四,语文72,英语91#王五,语文67,英语78"
    显示:
        姓名:王五,语文成绩:67,英语成绩78,总成绩:145
        姓名:李四,语文成绩:72,英语成绩91,总成绩:163
        姓名:张三,语文成绩:89,英语成绩75,总成绩:164

public class StudentInfo {
    public static void main(String[] args) {
        String input1 = "张三,语文89,英语75#李四,语文72,英语91#王五,语文67,英语78";
        
        // 将字符串解析为学生信息列表
        List studentInfoList = Arrays.asList(input1.split("#"));
        
        // 创建学生对象数组
        Student[] students = new Student[studentInfoList.size()];

        // 解析学生信息并存储到学生对象数组中
        for (int i = 0; i < studentInfoList.size(); i++) {
            String studentInfo = studentInfoList.get(i);
            String[] infoArray = studentInfo.split(",");
            String name = infoArray[0];
            int chineseScore = Integer.parseInt(infoArray[1].substring(2));
            int englishScore = Integer.parseInt(infoArray[2].substring(2));
            int totalScore = chineseScore + englishScore;
            students[i] = new Student(name, chineseScore, englishScore, totalScore);
        }

        // 按总成绩排序
        Arrays.sort(students, Comparator.comparingInt(Student::getTotalScore));

        // 显示学生信息
        for (int i = students.length - 1; i >= 0; i--) {
            Student student = students[i];
            System.out.println("姓名:" + student.getName() + ",语文成绩:" + student.getChineseScore() +
                    ",英语成绩:" + student.getEnglishScore() + ",总成绩:" + student.getTotalScore());
        }
    }
}

class Student {
    private String name;
    private int chineseScore;
    private int englishScore;
    private int totalScore;

    public Student(String name, int chineseScore, int englishScore, int totalScore) {
        this.name = name;
        this.chineseScore = chineseScore;
        this.englishScore = englishScore;
        this.totalScore = totalScore;
    }

    public String getName() {
        return name;
    }

    public int getChineseScore() {
        return chineseScore;
    }

    public int getEnglishScore() {
        return englishScore;
    }

    public int getTotalScore() {
        return totalScore;
    }
}

4、从键盘上输入一个字符串,利用字符串类提供的方法将大写字母转变为小写字母,小写    字母转变为大写字母,再将前后字符对换,然后输出最后结果。

import java.util.Scanner;

public class StringTransformation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入一个字符串:");
        String input = scanner.nextLine();

        // 将大写字母转换为小写字母,小写字母转换为大写字母
        String transformed = "";
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            System.out.println(c);
            if (Character.isUpperCase(c)) {
                transformed += Character.toLowerCase(c);
            } else if (Character.isLowerCase(c)) {
                transformed += Character.toUpperCase(c);
            } else {
                transformed += c;
            }
        }

        // 将前后字符对换
        StringBuilder reversed = new StringBuilder(transformed);
        reversed.reverse();

        System.out.println("转换后的结果:" + reversed.toString());
    }
}

5、定义一个集合大数据方向,大数据方向下面有三个班级人数分别是7个,10个,15个,使用循环给每个班级添加学生姓名,遍历大数据集合,显示每个班级的学生姓名。

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


public class BigData {
    public static void main(String[] args) {
        List> bigData = new ArrayList<>();

        // 添加三个班级
        bigData.add(new ArrayList<>());


        // 班级1
        bigData.add(new ArrayList<>()); // 班级2
        bigData.add(new ArrayList<>()); // 班级3

        // 定义每个班级的人数
        int[] classSizes = {7, 10, 15};

        // 使用循环给每个班级添加学生姓名
        for (int i = 0; i < bigData.size(); i++) {
            List classStudents = bigData.get(i);
            for (int j = 1; j <= classSizes[i]; j++) {
                classStudents.add("学生" + j);
            }
        }

        // 遍历大数据集合,显示每个班级的学生姓名
        for (int i = 0; i < bigData.size(); i++) {
            List classStudents = bigData.get(i);
            System.out.println("班级" + (i+1) + "的学生姓名:");
            for (String student : classStudents) {
                System.out.println(student);
            }
            System.out.println();
        }
    }
}

6、有字符串"aababcabcdabcde",获取字符串中每一个字母出现的次数。


        要求:
                 输出结果格式:a(5)b(4)c(3)d(2)e(1);
                 小括号中是前面字符出现的次数。
        提示:首先使用集合存储不重复的元素,然后用集合中的每一个元素和字符串中的每一个字符进行比较,统计各个字符出现的次数。

import java.util.HashMap;
import java.util.Map;

public class CharacterCount {
    public static void main(String[] args) {
        String str = "aababcabcdabcde";
        Map charCountMap = new HashMap<>();

        // 统计每个字符的出现次数
        for (char c : str.toCharArray()) {
            if (charCountMap.containsKey(c)) {
                int count = charCountMap.get(c);
                charCountMap.put(c, count + 1);
            } else {
                charCountMap.put(c, 1);
            }
        }

        // 输出结果
        StringBuilder result = new StringBuilder();
        for (Map.Entry entry : charCountMap.entrySet()) {
            result.append(entry.getKey()).append("(").append(entry.getValue()).append(")");
        }

        System.out.println(result.toString());
    }
}

7、键盘录入5个学生的姓名,英语成绩,语文成绩,数学成绩,按照以下要求显示学生的信息。从控制台输入学生的姓名和成绩,如果成绩大于100或小于0则抛出ChengjiFeifaException显示异常信息:成绩不合法!效果图:
        Java常见练手程序《“书写”百遍,其义自见》_第1张图片

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

public class StudentInfo {
    public static void main(String[] args) {
        List students = new ArrayList<>();

        Scanner scanner = new Scanner(System.in);

        // 录入学生信息
        for (int i = 0; i < 5; i++) {
            System.out.println("请输入第" + (i + 1) + "个学生的姓名:");
            String name = scanner.next();
            System.out.println("请输入第" + (i + 1) + "个学生的语文成绩:");
            int chineseScore = getValidScore(scanner);
            System.out.println("请输入第" + (i + 1) + "个学生的英语成绩:");
            int englishScore = getValidScore(scanner);
            System.out.println("请输入第" + (i + 1) + "个学生的数学成绩:");
            int mathScore = getValidScore(scanner);

            students.add(new Student1(name, chineseScore, englishScore, mathScore));
        }

        // 按总成绩排序
        students.sort(Comparator.comparingInt(Student1::getTotalScore).reversed());

        // 显示学生信息
        System.out.println("学生信息如下:");
        for (Student1 student : students) {
            System.out.println("姓名:" + student.getName() + ",语文成绩:" + student.getChineseScore() +
                    ",英语成绩:" + student.getEnglishScore() + ",数学成绩:" + student.getMathScore() +
                    ",总成绩:" + student.getTotalScore());
        }
    }

    private static int getValidScore(Scanner scanner) {
        int score;
        while (true) {
            score = scanner.nextInt();
            if (score < 0 || score > 100) {
                try {
                    throw new ChengjiFeifaException("成绩不合法!");
                } catch (ChengjiFeifaException e) {
                    System.out.println("异常信息:" + e.getMessage());
                }
            } else {
                break;
            }
        }
        return score;
    }
}

class Student1 {
    private String name;
    private int chineseScore;
    private int englishScore;
    private int mathScore;
    private int totalScore;

    public Student1(String name, int chineseScore, int englishScore, int mathScore) {
        this.name = name;
        this.chineseScore = chineseScore;
        this.englishScore = englishScore;
        this.mathScore = mathScore;
        this.totalScore = chineseScore + englishScore + mathScore;
    }

    public String getName() {
        return name;
    }

    public int getChineseScore() {
        return chineseScore;
    }

    public int getEnglishScore() {
        return englishScore;
    }

    public int getMathScore() {
        return mathScore;
    }

    public int getTotalScore() {
        return totalScore;
    }
}

class ChengjiFeifaException extends Exception {
    public ChengjiFeifaException(String message) {
        super(message);
    }
}

 

你可能感兴趣的:(Java,笔记)