-4

How can I assign a specific value to a string without using arrays or enumerations?

Example: 1 for "king", 2 for "queen" 3 for "guard". And then use random generator to generate between 1 and 3.

leftaroundabout
  • 117,950
  • 5
  • 174
  • 319

1 Answers1

1

Here is a more complete select case approach:

public static String toName(int value) {
  select(value) {
    case 1: return "king";
    case 2: return "queen";
    case 3: return "guard";
  }
  return null; //no matched value
}

Then borrowing this randomWithRange() from AusCBloke you can use it like this:

System.out.println(toName(randomWithRange(1,3)));
Community
  • 1
  • 1
Jason Sperske
  • 29,816
  • 8
  • 73
  • 124
  • my eyes are on fire... static method, non-final input arguments, string literals, and return null? – SnakeDoc Nov 08 '13 at 20:12
  • It made feel a bit dirty to write as well, I would love to understand why arrays are to be avoided – Jason Sperske Nov 08 '13 at 20:14
  • So how do i use the random generator for these three case and compare to the user's answer – user2970322 Nov 08 '13 at 20:14
  • `Math.random() * ( maxVal - minVal )` – SnakeDoc Nov 08 '13 at 20:15
  • The problem is that i got a program where they ask me to "link" a integer to a string like i said before and then ask the user to guess what is the word for example king, queen or quard. if the user enter queen then quit the program else ask him again about three time. – user2970322 Nov 08 '13 at 20:20
  • maybe look into using a `HashMap`, it's keyed by default (you can use numbers or whatever), and then store the data associated with it. Then use a key (your number) and it will return the data associated with it. – SnakeDoc Nov 08 '13 at 20:31