1 Replies - 828 Views - Last Post: 22 August 2009 - 06:23 AM Rate Topic: -----

#1 japanir   User is offline

  • jaVanir
  • member icon

Reputation: 1014
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

enum problem

Post icon  Posted 22 August 2009 - 05:42 AM

Hi all!
i am reading data from a file, then use the String.split, and get a String[] variable for each line i read.
then i have a class to read the data.
the txt file looks like:
2,John,Group1;
3,Dan, Group2;
/.
/.
i split the line from the "\\,".
and get a String[].
public enum Group {
GROUP1, GROUP2, GROUP3;
}

class A {
private int num1;
private String name;
private Group group;

A(String[] data){
this.num = Integer.parseint(data[0]);
this.name = data[1];
this.group = ??///my problem
}
}



how do i convert a string variable into an enum? is it possible?
Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: enum problem

#2 horace   User is offline

  • D.I.C Lover
  • member icon

Reputation: 768
  • View blog
  • Posts: 3,832
  • Joined: 25-October 06

Re: enum problem

Posted 22 August 2009 - 06:23 AM

View Postjapanir, on 22 Aug, 2009 - 11:42 AM, said:

Hi all!
i am reading data from a file, then use the String.split, and get a String[] variable for each line i read.
then i have a class to read the data.
the txt file looks like:
2,John,Group1;
3,Dan, Group2;
/.
/.
i split the line from the "\\,".
and get a String[].

how do i convert a string variable into an enum? is it possible?
Thanks!

Java enums are not ints like C or C++
yoiu can read the enums using scanner to read a String then checking its enum value, e.g.
import java.util.*;

enum Group {GROUP1, GROUP2, GROUP3;}

public class A {

   public  static void main(String a[])
	{
	 Scanner sc = new Scanner(System.in);
		for (Group algo : Group.values())
				 System.out.println(algo);
	 while(true)
	  // read strings from Scanner - display Group value or throw exception
	  try
		{
		System.out.print ("enter Group value ? ");
		System.out.println(" Group value " + Group.valueOf(sc.next()));
		}
	  catch (IllegalArgumentException m)
		{ System.out.println("  Error: " + m);
	  }		
	}
}


example run
GROUP1
GROUP2
GROUP3
enter Group value ? GROUP1
 Group value GROUP1
enter Group value ? HHHHH
  Error: java.lang.IllegalArgumentException: No enum const class Group.HHHHH
enter Group value ? GROUP2
 Group value GROUP2
enter Group value ? Group1
  Error: java.lang.IllegalArgumentException: No enum const class Group.Group1
enter Group value ? 


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1