1. 程式人生 > 實用技巧 >列舉enum簡單響應碼案例

列舉enum簡單響應碼案例

狀態碼列舉類程式碼:

package demo;

public enum ERROR {
    

    SUCCESS(200,"響應成功"),
    ERR(500,"響應失敗");
    
    private int code;
    private String message;
    
    ERROR(int code,String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    
public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }

測試案例:

package demo;

import java.util.Scanner;

public class R{
    
    public static
void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); if (str.equals("yes")) { System.out.println(ERROR.SUCCESS.getMessage()); }else if(str.equals("no")){ System.out.println(ERROR.ERR.getMessage()); } } }

執行結果:(輸入yes和no)