logo

Java Enum toString() metode

Enum klases metode toString() atgriež šīs enum konstantes nosaukumu, kā tas ir deklarācijā.

ToString() metodi var ignorēt, lai gan tā nav būtiska.

Sintakse

 public String toString() 

Parametri

TAS

Ignorēt:

Enum klases metode toString() ignorē objektu klases metodi toString().

Atdeves vērtība

Metode toString() atgriež šīs enum konstantes nosaukumu.

1. piemērs

 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()); } } } 
Izmēģiniet to tagad

Izvade:

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

2. piemērs

 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.'); } } } } } } 

Izvade:

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

3. piemērs

 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
You scored above 90'); } else if(str.equals(Grade.B.toString())){ System.out.println('Very good
You scored above 80 but below 90 '); } else if(str.equals(Grade.C.toString())){ System.out.println('Good
You scored above 70'); } else if(str.equals(Grade.D.toString())){ System.out.println('Fair
You scored aboved 50'); } else{ System.out.println('Word Hard
You failed!'); } } } 

Izvade:

 Enter your grade C Good You scored above 70