开始使用免费开始使用

使用 Enums 管理网页响应

使用 enums 管理 HTTP 响应,可以简化在 Web 应用中处理不同状态码的流程。本练习演示如何创建包含额外信息(如 HTTP 状态码)的 enums

本练习是课程的一部分

Java 中的输入/输出与流

查看课程

练习说明

  • HttpStatus 构造函数定义一个 int 参数 code
  • 当调用 getCode() 方法时,返回字段 code
  • 打印状态 OKHttpStatus 代码。

交互式实操练习

通过完成这段示例代码来试试这个练习。

public class HttpStatusExample {
    enum HttpStatus { 
        OK(200), NOT_FOUND(404);

        private int code;
		
        // Constructor for the HttpStatus with status code
        HttpStatus(____ code) { 
            this.code = code;
        }

        public int getCode() {
        	// Return the code for a specific HTTP status
            return ____;
        }
    }

    public static void main(String[] args) {
    	// Call method to print the status code
        System.out.println(HttpStatus.OK.____()); 
    }
}
编辑并运行代码