2024-08-27

在Java中,异常处理是一种结构化的程序出错处理方式,它允许程序中的错误被捕捉并处理,而不是让程序崩溃。以下是一些与《第一行代码JAVA》中异常处理相关的练习题:

  1. 请编写一个程序,它尝试打开一个不存在的文件,并捕获可能发生的异常。



import java.io.FileInputStream;
import java.io.FileNotFoundException;
 
public class OpenFileExample {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("nonexistentfile.txt");
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到异常:" + e.getMessage());
        } catch (Exception e) {
            System.out.println("其他异常:" + e.getMessage());
        }
    }
}
  1. 请编写一个程序,它尝试执行除以零的操作,并捕获可能发生的异常。



public class DivisionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("算术异常:" + e.getMessage());
        } catch (Exception e) {
            System.out.println("其他异常:" + e.getMessage());
        }
    }
}
  1. 请编写一个程序,它尝试分配一个超出JVM内存大小的数组,并捕获可能发生的异常。



public class OutOfMemoryExample {
    public static void main(String[] args) {
        try {
            int[] array = new int[1024 * 1024 * 1024]; // 尝试分配1GB的内存
        } catch (OutOfMemoryError e) {
            System.out.println("内存溢出异常:" + e.getMessage());
        } catch (Exception e) {
            System.out.println("其他异常:" + e.getMessage());
        }
    }
}
  1. 请编写一个程序,它尝试打开一个不存在的网络连接,并捕获可能发生的异常。



import java.net.Socket;
import java.net.UnknownHostException;
 
public class NetworkConnectionExample {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("nonexistenthost", 80);
        } catch (UnknownHostException e) {
            System.out.println("未知主机异常:" + e.getMessage());
        } catch (Exception e) {
            System.out.println("其他异常:" + e.getMessage());
        }
    }
}
  1. 请编写一个程序,它尝试序列化一个不可序列化的对象,并捕获可能发生的异常。



import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.IOException;
 
public class SerializationExample {
    public static void main(String[] args) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("temp.ser"));
            oos.writeObject(new NonSerializableClass());
2024-08-27

报错解释:

java.lang.IllegalArgumentException 是一个表示向方法传递了非法或不合适参数时抛出的异常。在这个特定的错误日志中,错误信息被截断了,没有完整显示,但从给出的部分可以推测,错误信息可能是指时间单位不足。例如,在使用某些库进行时间间隔操作时,可能需要指定时间单位,如天、小时、分钟等,如果最后一个时间单位没有提供足够的时间数值,可能会触发这个异常。

解决方法:

  1. 检查触发异常的代码行,确认时间间隔操作中所有时间单位是否有效且符合预期。
  2. 确保传递给方法的时间参数满足方法的要求,例如,如果方法期望一个小时的时间间隔,确保提供的参数大于0小时。
  3. 如果是使用第三方库或框架,查看相关文档,确保按照正确的方式传递时间参数。
  4. 如果错误信息未能完全显示,尝试查找完整的错误堆栈跟踪信息来获取更多细节。

请根据实际情况调整解决方案,以确保问题得到解决。

2024-08-27

在JavaScript中,输出内容到页面通常使用document.write()或者使用console.log()在浏览器的控制台中输出内容。

  1. document.write()方法:



document.write('Hello, World!');

这段代码会将字符串'Hello, World!'写入到HTML文档流中。如果这段代码在页面加载后执行,它会重写整个页面的内容。

  1. console.log()方法:



console.log('Hello, World!');

这段代码会在浏览器的控制台中输出字符串'Hello, World!',通常用于调试。

注意:document.write()方法在实际开发中不推荐使用,因为它有可能会覆盖整个文档流,使页面呈现不可预期的结果。在生产环境中,更常见的是使用DOM操作来动态地改变页面内容。例如,使用document.getElementById()element.innerHTML来更新特定元素的内容。

2024-08-27



public class WhileLoopExample {
    public static void main(String[] args) {
        int count = 1;
 
        // 使用 while 循环打印数字 1 到 5
        while (count <= 5) {
            System.out.println("Count: " + count);
            count++;
        }
 
        // 使用 while 循环计算从 1 加到 100 的和
        int sum = 0;
        int i = 1;
        while (i <= 100) {
            sum += i;
            i++;
        }
        System.out.println("Sum from 1 to 100: " + sum);
    }
}

这段代码首先使用一个while循环来打印数字1到5,然后使用另一个while循环计算从1加到100的和。这两个例子都展示了while循环的基本用法,并且在循环中修改循环变量以确保循环能够在适当的条件下终止。

2024-08-27

Java 注解(Annotations)是 JDK 5.0 引入的,提供了一种安全的类似注释的机制,用来将任何的信息或元数据(不改变程序运行的数据)关联到你的代码。

JDK 内置了三种基本注解:

  1. @Override:用于标识当前方法覆盖了父类的方法。
  2. @Deprecated:用于标识当前元素(类、方法等)不再推荐使用,可能存在更好的选择。
  3. @SuppressWarnings:用于通知 Java 编译器忽略指定的警告。

除了这三个 JDK 内置注解,我们还可以自定义注解。

自定义注解需要使用到四种元注解:

  1. @Target:指定注解可以应用的程序元素类型。
  2. @Retention:指定注解的策略:源码、类文件或者运行时。
  3. @Documented:指定注解应该被 javadoc 工具记录。
  4. @Inherited:指定注解可以被子类继承。

下面是一个简单的自定义注解的例子:




import java.lang.annotation.*;
 
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() default "default";
}
 
class MyClass {
    @MyAnnotation(value = "Hello")
    public void myMethod() {
        // 方法实现
    }
}
 
public class AnnotationExample {
    public static void main(String[] args) {
        if (MyClass.class.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation annotation = MyClass.class.getAnnotation(MyAnnotation.class);
            System.out.println(annotation.value());
        }
    }
}

在这个例子中,我们定义了一个名为 MyAnnotation 的注解,并将其应用到 MyClass 类的 myMethod 方法上。然后在 main 方法中,我们检查 MyClass 是否具有 MyAnnotation,并打印出注解的 value 值。

2024-08-27



import java.io.*;
import java.net.*;
 
public class TCPCommunication {
    public static void main(String[] args) {
        // 创建服务器端的ServerSocket对象
        ServerSocket serverSocket = null;
        // 创建客户端的Socket对象
        Socket clientSocket = null;
        // 创建输出流
        PrintWriter printWriter = null;
        // 创建输入流
        BufferedReader bufferedReader = null;
 
        try {
            // 创建服务器端的ServerSocket,并监听10000端口
            serverSocket = new ServerSocket(10000);
            System.out.println("服务器启动,等待客户端连接...");
 
            // 服务器端进入阻塞状态,等待客户端连接
            clientSocket = serverSocket.accept();
            System.out.println("客户端连接成功!");
 
            // 获取输出流,并构造PrintWriter对象
            OutputStream outputStream = clientSocket.getOutputStream();
            printWriter = new PrintWriter(outputStream, true);
 
            // 获取输入流,并构造BufferedReader对象
            InputStream inputStream = clientSocket.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
 
            // 服务器端向客户端发送消息
            printWriter.println("你好,客户端!");
 
            // 服务器端接收客户端发送的消息
            String message = bufferedReader.readLine();
            System.out.println("客户端说:" + message);
 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
                if (clientSocket != null) {
                    clientSocket.close();
                }
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

这段代码展示了如何使用Java的ServerSocketSocket类创建一个简单的TCP服务器端和客户端通信的例子。服务器端监听10000端口,并接收客户端的连接请求。服务器端向客户端发送一条消息,并接收客户端发送回来的响应。代码中包含了异常处理和资源关闭的正确做法。

2024-08-27

在Java中提交Flink任务到YARN集群,你可以使用Flink提供的YARN客户端API。以下是一个简化的Java代码示例,展示了如何提交一个简单的Flink任务到YARN集群:




import org.apache.flink.client.deployment.ClusterSpecification;
import org.apache.flink.client.deployment.DefaultClusterClientServiceLoader;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.GlobalConfiguration;
import org.apache.flink.yarn.YarnClusterDescriptor;
 
public class FlinkYarnJobSubmitter {
    public static void main(String[] args) throws Exception {
        // 设置Flink配置
        Configuration conf = new Configuration();
        conf.setString("yarn.application.id", "application_1234_0001"); // 示例YARN应用ID
        conf.setString("yarn.application.queue", "default"); // YARN队列名
        conf.setString("yarn.cluster.id", "ycluster_1234"); // YARN集群ID
        GlobalConfiguration.loadFlags(conf);
 
        // 创建YARN集群描述器
        YarnClusterDescriptor clusterDescriptor = new YarnClusterDescriptor(
            conf,
            "flink-app", // Flink应用名称
            "./conf", // Flink配置目录
            1, // TaskManager数量
            1024 // 每个TaskManager的内存大小(MB)
        );
 
        // 提交任务
        ClusterSpecification clusterSpecification = clusterDescriptor.getClusterSpecification(conf);
        ClusterClient<String> client = clusterDescriptor.deployJobCluster(
            clusterSpecification,
            "./conf", // Flink配置目录
            1, // JobManager的内存大小(MB)
            new DefaultClusterClientServiceLoader());
 
        // 提交作业
        client.run("classpath:/path/to/your/job.jar", "org.myorg.MyJob", "--arg1", "--arg2");
 
        // 关闭客户端
        client.close();
 
        // 关闭集群描述器
        clusterDescriptor.close();
    }
}

确保你的Flink任务jar包和所需的依赖都已经准备好,并且相关的Flink配置文件(如flink-conf.yaml)都放在指定的目录中。

在实际部署时,你需要根据你的YARN集群和Flink版本调整配置参数,并且可能需要处理安全认证和资源配额等问题。

2024-08-27

在Java中使用EasyExcel实现Excel的动态多级联动下拉列表,可以通过创建一个内联的名称区域(Name Range),并在该区域中使用MATCH+OFFSET函数来动态生成下拉列表的选项。

以下是一个简化的代码示例,展示如何在一个已有的EasyExcel工作簿中添加一个内联名称区域,并设置一个单元格的下拉列表:




import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.handler.AbstractColumnWidthStyleStrategy;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellRangeAddressList;
 
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
public class EasyExcelDynamicDropdownExample {
 
    public static void main(String[] args) throws IOException {
        // 假设已有一个Excel文件
        File existingFile = new File("example.xlsx");
 
        // 打开这个文件,准备写入
        EasyExcel.write(existingFile)
                .registerWriteHandler(new AbstractColumnWidthStyleStrategy() {
                    @Override
                    protected void setColumnWidth(Sheet sheet, int column, int width) {
                        sheet.setColumnWidth(column, width * 256);
                    }
                })
                .sheet("Sheet1")
                .doWrite(() -> {
                    Workbook workbook = new HSSFWorkbook(); // 或者 new XSSFWorkbook() 根据需要使用
                    Sheet sheet = workbook.getSheetAt(0);
                    // 假设我们要为B2单元格创建下拉列表
                    Row row = sheet.getRow(1);
                    if (row == null) {
                        row = sheet.createRow(1);
                    }
                    Cell cell = row.getCell(1);
                    if (cell == null) {
                        cell = row.createCell(1);
                    }
 
                    // 设置下拉列表的数据区域
                    String reference = "A1:A10"; // 假设下拉列表数据在A1:A10
                    CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(
                            0, //起始行(从0开始)
                            10, //结束行
                            0, //起始列(从0开始)
                            0  //结束列
                    );
 
                    // 创建名称区域
                    DVConstraint constraint = DVConstraint.createFormulaListConstraint("INDIRECT(ADDRESS(1,COLUMN(),4,$A$1))");
                    DataValidation 
2024-08-27



import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 
public class DateTimeExample {
    public static void main(String[] args) {
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前日期时间: " + now);
 
        // 使用DateTimeFormatter格式化日期时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        System.out.println("格式化后的日期时间: " + formattedNow);
 
        // 解析字符串为LocalDateTime对象
        String dateTimeString = "2023-03-25 15:30:00";
        LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, formatter);
        System.out.println("解析的日期时间: " + parsedDateTime);
 
        // 计算两个日期时间之间的差异
        LocalDateTime pastDateTime = LocalDateTime.of(2022, 3, 25, 15, 30);
        long daysBetween = ChronoUnit.DAYS.between(pastDateTime, now);
        System.out.println("与当前日期相差的天数: " + daysBetween);
    }
}

这段代码展示了如何使用Java的LocalDateTime类来获取当前日期时间、格式化日期时间、解析字符串为日期时间,以及计算两个日期时间之间的差异。这是一个简单的日期时间处理例子,对于开发者来说具有很好的教育意义。

2024-08-27



import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
 
import java.util.HashMap;
import java.util.Map;
 
public class DictionaryConverter implements Converter<String> {
 
    private Map<String, String> dictionary = new HashMap<>();
 
    public DictionaryConverter(Map<String, String> dictionary) {
        this.dictionary = dictionary;
    }
 
    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }
 
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }
 
    @Override
    public WriteCellData convertToExcelData(String value, WriteSheetHolder writeSheetHolder,
                                            WriteCellData writeCellData, GlobalConfiguration globalConfiguration) {
        String convertedValue = dictionary.get(value);
        if (convertedValue != null) {
            return new WriteCellData(convertedValue);
        }
        return new WriteCellData(value);
    }
}

这个代码示例展示了如何实现一个自定义的转换器DictionaryConverter,它接收一个字符串映射的字典,并且在将Java对象转换为Excel单元格数据时使用这个映射。如果字典中包含了字段的映射值,则转换后的数据会使用字典中的值。这种方式可以用于处理数据的编码或者是格式化等场景。