Results 1 to 6 of 6
Like Tree1Likes
  • 1 Post By wsaryada

Thread: How do I get a random value from an enum?

  1. #1
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default How do I get a random value from an enum?

    I tried using Random for it, but I could only get it to work for arrays, it probably can work for lists too. Strings arrays are fine and all, but in the future I think it will be a good idea to have atk, def, and health be different depending on the enemy (The enum currently is just enemy names) instead of using an Enemy object.

    The whole game so far, I doubt you'll need it, but who knows.

    Java Code:
    import java.util.*;
    
    
    public class Main{
    	
    	static Player player = new Player(100, 10, 10);
    	
    	public static void main(String[] args){
    		
    		String[] monsterNames = {"Zombie", "Skeleton", "Vampire", "Ghost", "Warlock", "Troll"};
    		
    		boolean gameInProgress = true;
    		int gameState = 0;
    		
    		Random rnd = new Random();
    		String type = monsterNames[rnd.nextInt(monsterNames.length)];
    		Enemy enemy = new Enemy(type, 100, 10, 2, 1);
    		enemy.setState(true);
    		
    		while(gameInProgress){
    			if(gameState == 0){
    				System.out.println("GAME MENU\n");
    				System.out.println("[1] Start your quest!");
    				System.out.println("[2] Quit");
    				
    				int choice = getInputFromPlayer();
    				gameState = choice;
    				
    				if(gameState > 2 || gameState < 0){
    					System.err.println("Invalid number.\n");
    					gameState = 0;
    				}
    				
    			}else if(gameState == 1){
    				
    				//Battle code
    				
    				if(enemy.getHealth() <= 0){
    					enemy.setHealth(0);
    					System.out.println(type + " killed! \nCreating new enemy!");
    					enemy.setState(false);
    				}
    				
    				if(!enemy.getState()){
    					type = monsterNames[rnd.nextInt(monsterNames.length)];
    					enemy.setName(type);
    					enemy.setHealth(100);
    					enemy.setState(true);
    				}
    				
    				System.out.println("\n" + enemy.getName() + "\n");
    				System.out.println("Health: " + enemy.getHealth());
    				
    				enemy.command(rnd, player);
    				
    				try{
    					Command com = getCommandFromPlayer();
    					battle(com, enemy);
    				}catch(CommandException e){
    					System.out.println("Invalid command, try again");
    				}
    				
    				
    			}else if(gameState == 2){
    				gameInProgress = false;
    			}
    		}
    	}
    	
    	private static void battle(Command com, Enemy enemy) {
    		if(com.equals(Command.ATTACK)){
    			
    			Random rnd = new Random();
    			int tempHealth = enemy.getHealth();
    			int damage = rnd.nextInt(player.getAtk()) + 5 - rnd.nextInt(enemy.getDef()) + 5;
    			tempHealth -= damage;
    			enemy.setHealth(tempHealth);
    			
    			System.out.println("You did " + damage + " damage to " + enemy.getName());
    			
    		}else if(com.equals(Command.DEFEND)){
    			
    		}else if(com.equals(Command.ITEMS)){
    			
    		}
    	}
    
    	public static Command getCommandFromPlayer() throws CommandException{
    		System.out.println("Enter command: ");
    		Scanner sc = new Scanner(System.in);
    		String command = sc.nextLine();
    		for(Command com : Command.values()){
    			if(com.getComName().equalsIgnoreCase(command) || com.getShortComName().equalsIgnoreCase(command)){
    				return com;
    			}
    		}
    		throw new CommandException(command);
    	}
    
    	public static int getInputFromPlayer(){
    		Scanner sc = new Scanner(System.in);
    		System.out.print("Please input your choice: ");
    		try{
    			int choice = sc.nextInt();
    			return choice;
    		}catch(Exception e){
    			System.err.println("Invalid input, please input a number.\n");
    		}
    		return 0;
    	}
    }
    Java Code:
    import java.util.*;
    
    public class Enemy {
    	
    	private String type;
    	private int health;
    	private int atk;
    	private int def;
    	private int potions;
    	private boolean state;
    	
    	public Enemy(String type, int health, int atk, int def, int potions){
    		this.type = type;
    		this.health = health;
    		this.atk = atk;
    		this.def = def;
    		this.potions = potions;
    	}
    	
    	public int getAtk(){
    		return atk;
    	}
    	
    	public String getName(){
    		return type;
    	}
    	
    	public int getHealth(){
    		return health;
    	}
    	
    	public int getDef(){
    		return def;
    	}
    	
    	public void setHealth(int health){
    		this.health = health;
    	}
    
    	public boolean getState(){
    		return state;
    	}
    	
    	public void setState(boolean state){
    		this.state = state;
    	}
    	
    	public void command(Random r, Player player){
    		int rnd = r.nextInt(100);
    		
    		if(rnd <= 60){
    			//Attack
    			int tempHealth = player.getHealth();
    			int damage = r.nextInt(atk) + 5 - r.nextInt(player.getDef()) + 5;
    			tempHealth -= damage;
    			player.setHealth(tempHealth);
    			System.out.println(type + " did " + damage + " damage!");
    			
    		}else if(rnd > 60 && rnd < 80){
    			//Defense
    			System.out.println("Defending.");
    			
    		}else if(rnd >= 80){
    			//Items
    			int healAmount = r.nextInt(50) + 20;
    			
    			if(potions > 0){
    				health += healAmount;
    				potions -= 1;
    				System.out.println(type + " healed itself for " + healAmount);
    				
    				if(health > 100) health = 0;
    				
    			}else{
    				//If no potions available, attack.
    				
    				int tempHealth = player.getHealth();
    				int damage = r.nextInt(atk) + 5 - r.nextInt(player.getDef()) + 5;
    				tempHealth -= damage;
    				player.setHealth(tempHealth);
    				System.out.println(type + " did " + damage + " damage!");
    			}
    		}
    	}
    	
    	public void setName(String type){
    		this.type = type;
    	}
    }
    Java Code:
    import java.util.*;
    
    public enum Type {
    	ZOMBIE("Zombie"), SKELETON("Skeleton"), VAMPIRE("Vampire"), SLIME("Slime");
    	
    	private String monsterName;
    	
    	private Type(String monsterName){
    		this.monsterName = monsterName;
    	}
    	
    	public String getName(){
    		return monsterName;
    	}
    }
    Java Code:
    public enum Command{
    	ATTACK("attack", "a"), DEFEND("defend", "d"), ITEMS("inventory", "i");
    	
    	private String comName;
    	private String shortComName;
    	
    	private Command(String comName, String shortComName){
    		this.comName = comName;
    		this.shortComName = shortComName;
    	}
    	
    	public String getComName(){
    		return comName;
    	}
    	
    	public String getShortComName(){
    		return shortComName;
    	}
    }
    Java Code:
    public class CommandException extends Exception{
    	public CommandException(String com){
    		super(com);
    	}
    }
    Java Code:
    public class Player{
    	
    	private int health;
    	private int atk;
    	private int def;
    	
    	public Player(int health, int atk, int def){
    		this.health = health;
    		this.atk = atk;
    		this.def = def;
    	}
    	
    	public int getHealth(){
    		return health;
    	}
    	
    	public int getAtk(){
    		return atk;
    	}
    	
    	public int getDef(){
    		return def;
    	}
    	
    	public void setHealth(int health){
    		this.health = health;
    	}
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How do I get a random value from an enum?

    That's a lot of code. Can you show us where you're trying to get a random value?

  3. #3
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I get a random value from an enum?

    Java Code:
    String[] monsterNames = {"Zombie", "Skeleton", "Vampire", "Ghost", "Warlock", "Troll"};
             
            Random rnd = new Random();
            String type = monsterNames[rnd.nextInt(monsterNames.length)];
    I tried to get it from the enum with a for loop, and by itself, and all types of stuff, so I gave up and tested it with a string array and it works fine. But like I said, when I add more stuff to the enum I will need it again.

  4. #4
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    760
    Rep Power
    8

    Default Re: How do I get a random value from an enum?

    You can do something like this:

    Java Code:
    enum Monster {
        Zombie, Skeleton, Vampire, Ghost, Warlock, Troll;
    
        public static Monster getRandomMonster() {
            Random random = new Random();
            return values()[random.nextInt(values().length)];
        }
    }
    
    public static void main(String[] args) {
        Monster monster = Monsters.getRandomMonster();
    }
    Fubarable likes this.

  5. #5
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I get a random value from an enum?

    I get an error for some reason, although I'm fairly sure it's just something to do with my implementation. (BOTTOM)

    Java Code:
    import java.util.*;
    
    
    public class Main{
    	
    	static Player player = new Player(100, 10, 10);
    	
    	public static void main(String[] args){
    		
    		boolean gameInProgress = true;
    		int gameState = 0;
    		
    		Type type = Type.getRandomEnemy();
    		type.setState(true);
    		
    		while(gameInProgress){
    			if(gameState == 0){
    				System.out.println("GAME MENU\n");
    				System.out.println("[1] Start your quest!");
    				System.out.println("[2] Quit");
    				
    				int choice = getInputFromPlayer();
    				gameState = choice;
    				
    				if(gameState > 2 || gameState < 0){
    					System.err.println("Invalid number.\n");
    					gameState = 0;
    				}
    				
    			}else if(gameState == 1){
    				
    				//Battle code
    				
    				if(type.getHealth() <= 0){
    					type.setHealth(0);
    					System.out.println(type + " killed! \nCreating new enemy!");
    					type.setState(false);
    				}
    				
    				if(!type.getState()){
    					type = Type.getRandomEnemy();
    					type.setState(true);
    				}
    				
    				System.out.println("\n" + type.getName() + "\n");
    				System.out.println("Health: " + type.getHealth());
    				
    				type.command(new Random(), player);
    				
    				try{
    					Command com = getCommandFromPlayer();
    					battle(com, type);
    				}catch(CommandException e){
    					System.out.println("Invalid command, try again");
    				}
    				
    				
    			}else if(gameState == 2){
    				gameInProgress = false;
    			}
    		}
    	}
    	
    	private static void battle(Command com, Type type) {
    		if(com.equals(Command.ATTACK)){
    			
    			Random rnd = new Random();
    			int tempHealth = type.getHealth();
    			int damage = rnd.nextInt(player.getAtk()) + 5 - rnd.nextInt(type.getDef()) + 5;
    			tempHealth -= damage;
    			type.setHealth(tempHealth);
    			
    			System.out.println("You did " + damage + " damage to " + type.getName());
    			
    		}else if(com.equals(Command.DEFEND)){
    			
    		}else if(com.equals(Command.ITEMS)){
    			
    		}
    	}
    
    	public static Command getCommandFromPlayer() throws CommandException{
    		System.out.println("Enter command: ");
    		Scanner sc = new Scanner(System.in);
    		String command = sc.nextLine();
    		for(Command com : Command.values()){
    			if(com.getComName().equalsIgnoreCase(command) || com.getShortComName().equalsIgnoreCase(command)){
    				return com;
    			}
    		}
    		throw new CommandException(command);
    	}
    
    	public static int getInputFromPlayer(){
    		Scanner sc = new Scanner(System.in);
    		System.out.print("Please input your choice: ");
    		try{
    			int choice = sc.nextInt();
    			return choice;
    		}catch(Exception e){
    			System.err.println("Invalid input, please input a number.\n");
    		}
    		return 0;
    	}
    }
    Java Code:
    import java.util.*;
    
    public enum Type {
    	ZOMBIE("Zombie", 25, 5, 0, 0), SKELETON("Skeleton", 100, 3, 1, 1), VAMPIRE("Vampire", 100, 10, 3, 1), 
    	SLIME("Slime", 200, 1, 1, 0);
    	
    	private String monsterName;
    	private int monsterHealth;
    	private int monsterAtk;
    	private int monsterDef;
    	private int potions;
    	private boolean state;
    	
    	private Type(String monsterName, int monsterHealth, int monsterAtk, int monsterDef, int potions){
    		this.monsterName = monsterName;
    		this.monsterHealth = monsterHealth;
    		this.monsterAtk = monsterAtk;
    		this.monsterDef = monsterDef;
    		this.potions = potions;
    		this.state = false;
    	}
    	
    	public String getName(){
    		return monsterName;
    	}
    	
    	public static Type getRandomEnemy(){
    		Random random = new Random();
    		return values()[random.nextInt(values().length)];
    	}
    	
    	public int getAtk(){
    		return monsterAtk;
    	}
    
    	public int getHealth(){
    		return monsterHealth;
    	}
    	
    	public int getDef(){
    		return monsterDef;
    	}
    	
    	public void setHealth(int monsterHealth){
    		this.monsterHealth = monsterHealth;
    	}
    
    	public boolean getState(){
    		return state;
    	}
    	
    	public void setState(boolean state){
    		this.state = state;
    	}
    	
    	public void command(Random r, Player player){
    		int rnd = r.nextInt(100);
    		
    		if(rnd <= 60){
    			//Attack
    			int tempHealth = player.getHealth();
    			int damage = r.nextInt(monsterAtk) + 5 - r.nextInt(player.getDef()) + 5;
    			tempHealth -= damage;
    			player.setHealth(tempHealth);
    			System.out.println(monsterName + " did " + damage + " damage!");
    			
    		}else if(rnd > 60 && rnd < 80){
    			//Defense
    			System.out.println("Defending.");
    			
    		}else if(rnd >= 80){
    			//Items
    			int healAmount = r.nextInt(50) + 20;
    			
    			if(potions > 0){
    				monsterHealth += healAmount;
    				potions -= 1;
    				System.out.println(monsterName + " healed itself for " + healAmount);
    				
    				if(monsterHealth > 100) monsterHealth = 0;
    				
    			}else{
    				//If no potions available, attack.
    				
    				int tempHealth = player.getHealth();
    				int damage = r.nextInt(monsterAtk) + 5 - r.nextInt(player.getDef()) + 5;
    				tempHealth -= damage;
    				player.setHealth(tempHealth);
    				System.out.println(monsterName + " did " + damage + " damage!");
    			}
    		}
    	}
    	
    	public void setName(String type){
    		monsterName = type;
    	}
    }
    Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
    at java.util.Random.nextInt(Unknown Source)
    at Main.battle(Main.java:69)
    at Main.main(Main.java:52)


    At first I thought it might be because the damage was lower than 0, so I did this:

    Java Code:
    Random rnd = new Random();
    			int tempHealth = type.getHealth();
    			if(tempHealth - rnd.nextInt(player.getAtk()) + 5 - rnd.nextInt(type.getDef()) + 5 > 0){
    				int damage = rnd.nextInt(player.getAtk()) + 5 - rnd.nextInt(type.getDef()) + 5;
    				tempHealth -= damage;
    				type.setHealth(tempHealth);
    				System.out.println("You did " + damage + " damage to " + type.getName());
    			}
    but I still get the error, I'm assuming it has to do with the random.
    Last edited by Darkzombies; 12-11-2012 at 05:38 AM.

  6. #6
    Darkzombies is offline Senior Member
    Join Date
    Nov 2012
    Posts
    105
    Rep Power
    0

    Default Re: How do I get a random value from an enum?

    Vampire

    OUTPUT:
    -------------------------------
    Health: 85
    Vampire healed itself for 62
    Enter command:
    a
    You did 17 damage to Vampire
    VAMPIRE killed!
    --------------------------------
    Part of the problem, it only happens occasionally, sometimes it works, sometimes it doesn't. (It gives me an instant kill, not supposed too)

    Hmm... maybe it has something to do with

    Java Code:
    if(monsterHealth > 100) monsterHealth = 0;
    I'm a complete idiot, just ignore me, it was supposed to be

    Java Code:
    if(monsterHealth > 100) monsterHealth = 100;
    but in fact, it probably should be

    Java Code:
    if(monsterHealth > maxHealth) monsterHealth = maxHealth;
    Last edited by Darkzombies; 12-11-2012 at 08:05 AM.

Similar Threads

  1. Replies: 0
    Last Post: 01-23-2012, 10:12 AM
  2. public static enum vs enum class
    By Dipke in forum New To Java
    Replies: 3
    Last Post: 08-30-2011, 11:45 AM
  3. Setting values from One Enum type to another enum type.
    By reach2sudhakar in forum New To Java
    Replies: 3
    Last Post: 09-23-2010, 07:02 PM
  4. Replies: 14
    Last Post: 10-19-2009, 11:57 AM
  5. Replies: 8
    Last Post: 04-19-2009, 06:50 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •