Question:
I need help writing a code in java?
rony
2010-04-26 13:08:10 UTC
Hello I need help writing a java code. Basically all i want to do generate a magic 8 ball. I want the user to enter a question and have already answers written. I want to code to choose a random answer and just print it out. I know math.random will choose a random number but i don't how to do it with a string. Please Help!!!
Three answers:
Abhinav
2010-04-26 13:15:52 UTC
put all the string answers in an array, use math.random to generate a number between 0 and 7 and then just use that number to pick the string from the string array
Dustin
2010-04-26 13:22:04 UTC
so basically all you need to do is assign a set of numbers that Math.random() covers, to specific strings.



First of all when working with Math.random its importat to know that it comes up with a number between 0 and 1. Small numbers such as these can be difficult to manage so in my experience i always multiply it by 100. Making it a number between 1 and 100.



double randomNum = (Math.random() * 100);



Now we can assign the strings.

For example is you wanted to have 4 different strings that is could print out, you would need to assign different numbers to a string.



the "guts" of the code should look similar to whats below:



if(randomNum > 0 && <= 25)

{

System.out.println("No");

}

else if(randomNum > 25 && randomNum <= 50)

{

System.out.println("Yes");

}

else if(randomNum > 50 && randomNum <= 75)

{

System.out.println("Maybe");

}

else if(randomNum > 75 && randomNum <= 100)

{

System.out.println("Unclear, ask again.");

}



Hope this helps!!
2010-04-26 13:10:50 UTC
Just have an array of strings and then use the Math.Random to get you an index of the string.



So in the simplest sense:

String answers=new String[2];

answers[0]="Yes";

answers[1]="no";

Random rand=new Random();

System.out.println( answers[rand.nextInt(2)] );


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...