Java:编程

72°C 05-01-2025 notbyai
最近更新于:2025-01-06 13:30:31

1. 利用do…while语句,计算1!+2!+…100!

import java.math.BigInteger;

public class FactorialSum {
    public static void main(String[] args) {
        // 初始化变量
        int n = 1; // 当前的数
        BigInteger sum = BigInteger.ZERO; // 存储总和

        do {
            // 计算当前数的阶乘并累加到总和
            sum = sum.add(factorial(n));
            n++; // 递增到下一个数
        } while (n <= 100); // 条件:计算到 100

        // 输出结果
        System.out.println("1! + 2! + ... + 100! 的结果是:");
        System.out.println(sum);
    }

    // 计算阶乘的方法
    public static BigInteger factorial(int num) {
        BigInteger result = BigInteger.ONE; // 阶乘的初始值
        for (int i = 1; i <= num; i++) {
            result = result.multiply(BigInteger.valueOf(i));
        }
        return result;
    }
}

2. Fibonacci数列的第一项是0,第二项是1,以后各项都是前两项的和,编写方法求第n项的值。

import java.util.Scanner;

public class FibonacciRecursiveInput {
    public static void main(String[] args) {
// 创建 Scanner 对象,从键盘获取用户输入
Scanner scanner = new Scanner(System.in);

    // 提示用户输入 n
    System.out.print("请输入一个非负整数 n:");
    int n = scanner.nextInt();

    // 检查输入是否有效
    if (n < 0) {
        System.out.println("请输入一个非负整数!");
    } else {
        // 计算并输出 Fibonacci 数列的第 n 项
        System.out.println("Fibonacci 数列的第 " + n + " 项是:" + fibonacci(n));
    }

    // 关闭 Scanner
    scanner.close();
}

// 递归实现 Fibonacci
public static int fibonacci(int n) {
    if (n == 1) {
        return 0; // 第 0 项
    } else if (n == 2) {
        return 1; // 第 1 项
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2); // 前两项之和
    }
}

}

3. 计算1!+2!+3!+…+10!,其中阶乘的计算用方法实现。

public class FactorialSum {
    // 方法:计算阶乘
    public static long factorial(int n) {
        long result = 1;
        for (int i = 1; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    public static void main(String[] args) {
        long sum = 0;
        
        // 循环计算1! 到 10! 并累加
        for (int i = 1; i <= 10; i++) {
            sum += factorial(i); // 调用方法计算阶乘
        }
        
        // 输出结果
        System.out.println("1! + 2! + 3! + ... + 10! = " + sum);
    }
}

4. 打印以下杨辉三角形(打印10行)

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

public class YangHuiTriangle {
    public static void main(String[] args) {
        int rows = 10; // 要打印的行数
        int[][] triangle = new int[rows][rows];

        // 初始化杨辉三角
        for (int i = 0; i < rows; i++) {
            triangle[i][0] = 1; // 每行的第一个元素是1
            triangle[i][i] = 1; // 每行的最后一个元素是1
            for (int j = 1; j < i; j++) {
                triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
            }
        }

        // 打印杨辉三角(左对齐)
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.printf("%4d", triangle[i][j]); // 每个数字占4个字符宽度
            }
            System.out.println(); // 换行
        }
    }
}

5. 设计实现地址概念的类Address。Address具有属性:省份、市、街道、门牌号、邮编,具有能设置和获取属性的方法。

public class Address {
    // 属性:省份、市、街道、门牌号、邮编
    private String province;
    private String city;
    private String street;
    private String houseNumber;
    private String postalCode;

    // 构造方法:初始化地址信息
    public Address(String province, String city, String street, String houseNumber, String postalCode) {
        this.province = province;
        this.city = city;
        this.street = street;
        this.houseNumber = houseNumber;
        this.postalCode = postalCode;
    }

    // 默认构造方法(无参)
    public Address() {}

    // 获取和设置方法(Getter 和 Setter)

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getHouseNumber() {
        return houseNumber;
    }

    public void setHouseNumber(String houseNumber) {
        this.houseNumber = houseNumber;
    }

    public String getPostalCode() {
        return postalCode;
    }

    public void setPostalCode(String postalCode) {
        this.postalCode = postalCode;
    }

    // 输出完整地址的方法
    public String getFullAddress() {
        return province + "省, " + city + "市, " + street + "街道, 门牌号: " + houseNumber + ", 邮编: " + postalCode;
    }

    // 主函数示例
    public static void main(String[] args) {
        // 创建 Address 对象并设置属性
        Address address = new Address();
        address.setProvince("广东");
        address.setCity("广州");
        address.setStreet("天河路");
        address.setHouseNumber("100号");
        address.setPostalCode("510000");

        // 打印完整地址
        System.out.println("地址信息: " + address.getFullAddress());
    }
}

6. 设计一个圆类Circle,具有属性:圆心坐标x和y及圆半径r,除具有设置及获取属性的方法外,还具有计算周长的方法perimeter()和计算面积的方法 area()。再设计一个圆柱体类Cylinder,Cylinder继承自 Circle,增加了属性:高度h,增加了设置和获取h的方法、计算表面积的方法area()和计算体积的方法volume()。创建Cylinder的类对象,显示其所有属性,计算并显示其面积和体积。

// 定义圆类 Circle
class Circle {
    // 圆心坐标和半径
    private double x;
    private double y;
    private double r;

    // 构造方法
    public Circle(double x, double y, double r) {
        this.x = x;
        this.y = y;
        this.r = r;
    }

    // 设置和获取 x
    public void setX(double x) {
        this.x = x;
    }

    public double getX() {
        return this.x;
    }

    // 设置和获取 y
    public void setY(double y) {
        this.y = y;
    }

    public double getY() {
        return this.y;
    }

    // 设置和获取 r
    public void setR(double r) {
        this.r = r;
    }

    public double getR() {
        return this.r;
    }

    // 计算圆的周长
    public double perimeter() {
        return 2 * Math.PI * r;
    }

    // 计算圆的面积
    public double area() {
        return Math.PI * r * r;
    }
}

// 定义圆柱体类 Cylinder,继承自 Circle
class Cylinder extends Circle {
    // 圆柱体的高度
    private double h;

    // 构造方法
    public Cylinder(double x, double y, double r, double h) {
        super(x, y, r); // 调用父类构造方法
        this.h = h;
    }

    // 设置和获取 h
    public void setH(double h) {
        this.h = h;
    }

    public double getH() {
        return this.h;
    }

    // 获取圆的面积(保留父类的圆面积功能)
    public double baseArea() {
        return super.area(); // 调用父类的 area() 方法
    }

    // 计算圆柱体的表面积
    @Override
    public double area() {
        double baseArea = super.area(); // 圆的面积
        double sideArea = 2 * Math.PI * getR() * h; // 侧面积
        return 2 * baseArea + sideArea;
    }

    // 计算圆柱体的体积
    public double volume() {
        return super.area() * h; // 圆的面积乘以高度
    }
}

// 主类测试
public class Main {
    public static void main(String[] args) {
        // 创建一个圆柱体对象
        Cylinder cylinder = new Cylinder(0, 0, 5, 10);

        // 输出圆柱体的属性
        System.out.println("圆柱体的属性:");
        System.out.println("圆心坐标: (" + cylinder.getX() + ", " + cylinder.getY() + ")");
        System.out.println("半径: " + cylinder.getR());
        System.out.println("高度: " + cylinder.getH());

        // 计算并输出圆的周长和面积
        System.out.println("\n圆的周长: " + cylinder.perimeter());
        System.out.println("圆的面积: " + cylinder.baseArea()); // 使用 baseArea() 获取圆的面积

        // 计算并输出圆柱体的表面积和体积
        System.out.println("\n圆柱体的表面积: " + cylinder.area());
        System.out.println("圆柱体的体积: " + cylinder.volume());
    }
}

7. 编写一个程序,其功能是将两个文件中的内容合并到一个文件中。

import java.io.*;

public class FileMerger {

public static void main(String[] args) {
    // 文件路径可以自行修改
    String file1Path = "file1.txt"; // 第一个文件的路径
    String file2Path = "file2.txt"; // 第二个文件的路径
    String outputFilePath = "merged_file.txt"; // 输出文件的路径

    mergeFiles(file1Path, file2Path, outputFilePath);
}

/**
 * 将两个文件的内容合并到一个输出文件中
 *
 * @param file1Path 第一个文件的路径
 * @param file2Path 第二个文件的路径
 * @param outputFilePath 合并后的输出文件路径
 */
public static void mergeFiles(String file1Path, String file2Path, String outputFilePath) {
    // 使用 try-with-resources 确保流在使用后自动关闭
    try (
        BufferedReader reader1 = new BufferedReader(new FileReader(file1Path));
        BufferedReader reader2 = new BufferedReader(new FileReader(file2Path));
        BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))
    ) {
        // 读取第一个文件并写入输出文件
        String line;
        while ((line = reader1.readLine()) != null) {
            writer.write(line);
            writer.newLine(); // 换行
        }

        // 读取第二个文件并写入输出文件
        while ((line = reader2.readLine()) != null) {
            writer.write(line);
            writer.newLine(); // 换行
        }

        System.out.println("文件合并完成!输出文件路径:" + outputFilePath);

    } catch (IOException e) {
        // 捕获IO异常并打印错误信息
        System.err.println("发生错误:" + e.getMessage());
    }
}

}

8. 编写一个程序,分别统计并输出文本文件中元音字母a,e,i,o,u的个数。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class VowelCounter {
    public static void main(String[] args) {
        // 定义元音字母
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        int[] vowelCounts = new int[5]; // 用于统计 a, e, i, o, u 的个数

        // 文件路径(根据需要修改路径)
        String filePath = "input.txt";

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 转为小写以方便统计
                line = line.toLowerCase();

                // 遍历每个字符,统计元音
                for (char c : line.toCharArray()) {
                    for (int i = 0; i < vowels.length; i++) {
                        if (c == vowels[i]) {
                            vowelCounts[i]++;
                        }
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("读取文件时发生错误: " + e.getMessage());
            return;
        }

        // 输出统计结果
        System.out.println("文件中元音字母的统计结果:");
        for (int i = 0; i < vowels.length; i++) {
            System.out.println(vowels[i] + ": " + vowelCounts[i]);
        }
    }
}

评论留言

欢迎您,!您可以在这里畅言您的的观点与见解!

0 条评论