當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Enum toString()用法及代碼示例


Enum 類的 toString() 方法返回此枚舉常量的名稱,如聲明所包含的那樣。

toString() 方法可以被覆蓋,盡管它不是必需的。

用法

public String toString()

參數

NA

覆蓋:

Enum 類的 toString() 方法覆蓋了 Object 類的 toString() 方法。

返回值

toString() 方法返回此枚舉常量的名稱。

例子1

enum Planets{

Mercury, Venus, Earth, Mars, Jupiter,Uranus, Neptune;

}

public class Enum_toStringMethodExample1 {

public static void main(String[] args) {

System.out.println("Seven Planets:");

for(Planets planets:Planets.values()){

int i = planets.ordinal()+1;

System.out.println(i+" "+planets.toString());
        }
    }
}

輸出:

Seven Planets:
1 Mercury
2 Venus
3 Earth
4 Mars
5 Jupiter
6 Uranus
7 Neptune

例子2

import java.util.Scanner;

public class Enum_toStringMethodExample2 {

enum Position{

First ,Second,Third;
    }
enum Prize{

Gold ,Silver,Bronze;
    }
public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

System.out.println("Enter your positon:");

        String str =scanner.next();

for(Position pos:Position.values()){

int i = pos.ordinal();

//it will return the enum constant as String

String str1 =pos.toString();

if(str.equals(str1)){

for(Prize prize:Prize.values()){

int j= prize.ordinal();

if(i==j){

System.out.println("Congratulation! You have won a "+prize+" medal.");

                    }
                }
            }
        }
    }
}

輸出:

Enter your positon:
Second
Congratulation! You have won a Silver medal.

例子3

import java.util.Scanner;

public class Enum_toStringMethodExample3 {

enum Grade{

A ,B,C,D ,E;
    }
public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

System.out.println("Enter your grade");

        String str = scanner.next();

        String str1 =Grade.A.toString();

if(str.equals(str1)){

System.out.println("Excellent\nYou scored above 90");
            }
else if(str.equals(Grade.B.toString())){

System.out.println("Very good\nYou scored above 80 but below 90 ");
            }
else if(str.equals(Grade.C.toString())){

System.out.println("Good\nYou scored above 70");
            }

else if(str.equals(Grade.D.toString())){

System.out.println("Fair\nYou scored aboved 50");
            }

else{

System.out.println("Word Hard\nYou failed!");
            }
        }
    }

輸出:

Enter your grade
C
Good
You scored above 70



相關用法


注:本文由純淨天空篩選整理自 Java Enum toString() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。