開始使用免費開始

用 Enums 管理網頁回應

使用 enums 管理 HTTP 回應,可以簡化在網頁應用程式中處理不同狀態代碼的流程。這個練習會示範如何建立包含額外資訊(例如 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.____()); 
    }
}
編輯並執行程式碼