Hi, I'm writing a program using BlueJ Java. I Need to select random numbers and strings. The random numbers are easy, but I can't figure out how to randomize strings. I'm can't use integers and then an if-statement.
Can anyone help me for this? I tried to figure this out for while but nothing comes to mind.
String str = "";
Random rand = new Random();
i = rand.nextInt(4) + 1;
Maybe I'm missing something or I'm unaware of a method.
Someone else may have a better way to do this, but, here is my solution, you can generate random numbers from 0-25, then add 65 for capital letters, and add 97 for lower case.
This uses ascii to generate random characters which you can convert to strings. Look up what you can do with characters to turn them into strings, then loop a random number of times, each time creating a new character and appending it to a string.
Character (Java 2 Platform SE v1.4.2)
be creative !
Fill a list/array with letters (A-Z, a-z) and generate a random number from 0 to array/list size and take the letter at that index...
Or another idea could be to generate a random number from 97-122 for ascii lowercase letters (a-z)
char c = (char)(rand.nextInt('z'-'a' +1) + 'a');
Or for both (numbers and letters) you could use something like
or or or...
By string I mean a word, like "blue" or "car"
I thought of putting them in an array but I don't know if I'm allowed to. I'm trying to solve an exercise and the class has specific fields and methods I don't know if I can put an extra field. That's my main problem.
what fields can you have? The only way I can think of to randomize Strings that already exist is to populate an array with it then generate a random number from 0 to array length - 1, then use array[random num]
there's a person before with the same problem his post's name is "fish constructor"
I don't know how to post a uml...
I wrote that in the Fish constructor
Then i wrote a method called setType
int a2 = rand5.nextInt(1);
type = "herbivore";
type = "carnivore";
does it seem right?
public void setType(String tp)
type = tp;
u can put the string choices u want in array, and use the random class to generate an int from 0 to a number n , in ur case the length of the array, and then make it choose the number generated as the index for the the array element
if u want, see my post, i had the same problem but it is solved now
Where are you getting a random int and using it in an array to get the String? This has already been suggested to you I believe.