当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。