This question already has answers here:
How do I efficiently iterate over each entry in a Java Map?
(46 answers)
Closed 4 years ago.
I'm pretty new to Java and in an effort to learn more I'm trying to make a game whereby you're given a random lyric from a song, and then the song title and artist.
This would be pretty easy, however I wanted the lyric to be random, and then print the artist and song title using a seperate method. My problem is that I'm not sure how to go from printing one random string to printing a specific answer.
I currently have the lyrics and the answers in a hashmap with the lyrics as keys and answers as values, and can print random keys by turning them into an arraylist using this method
public void randomLyrics()
{
ArrayList<String> lyricKey = new ArrayList<String>(lyrics.keySet());
if(lyrics.size() > 0) {
Random rand = new Random();
int index = rand.nextInt(lyrics.size());
System.out.println(lyricKey.get(rand.nextInt(lyrics.size())));
}
}
however I'm pretty sure that this isn't the right way to go about it, and am not sure how I would go about printing the answers seperately.
Any help would be much appreciated.
Also just to clarify, I want to call a method (randomLyrics) which will display a random lyric such as "that's me in the corner, that's me in the spotlight" and then call a seperate method (answer) which would then print "Losing My Religion - R.E.M."
Many thanks
Here is full example run this program multiple times you will get some random value:-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
public class HashM {
public static void main(String[] args) {
HashMap<String, String> lyrics = new HashMap<>();
// KEY :- Lyrics AND Value is Album Name
lyrics.put("that's me in the corner, that's me in the spotlight", "Losing My Religion - R.E.M.");
lyrics.put("I will try not to breathe I can hold my head still with my hands at my knees",
"Automatic for the People");
lyrics.put("Eu não aturo mais Sou um trator", "É Duda Brack");
randomLyrics(lyrics);
}
public static void randomLyrics(HashMap<String, String> lyrics) {
ArrayList<String> lyricKey = new ArrayList<String>(lyrics.keySet());
if (lyrics.size() > 0) {
Random rand = new Random();
int index = rand.nextInt(lyrics.size());
System.out.println("###::####Your Random Number is :-" + rand.nextInt(lyrics.size()));
System.out.println(lyricKey.get(rand.nextInt(lyrics.size())));
}
}
}
Related
I'm writing this golf program for my class that takes a .txt that has 5 numbers per row and 18 rows. The first number in each row is the par for that hole. The other four numbers are for each player.
I kind of have my own spin on this program, though. I wrote another program to create the .txt file with random numbers. The output is dependent on how many players there are which is inputted by the user.
Anyway, I've gotten the .txt generator just fine and I've gotten the Golf program to accurately count how many players there are. What I can't figure out is how to create that number of arrays with different names. I want each array to be int player1[18], player2[18], player3[18], etc.
Here's my code up to that point:
import java.util.Scanner;
import java.io.*;
public class Golf
{
public static void main(String[] args) throws java.io.IOException
{
Scanner countScan = new Scanner(new File("golfscores.txt"));
Scanner file = new Scanner(new File("golfscores.txt"));
//------------------------------------------------------------
// Counting the number of players
//
// This takes the number of integers in the file, divides it by
// the 18 holes in the course and subtracts 1 for the par.
//
// I needed to count the players because it's a variable that
// can change depending on how many players are entered in the
// java program that creates a random scorecard.
//------------------------------------------------------------
int players = 0;
for (int temp = 0; countScan.hasNextInt(); players++)
temp = countScan.nextInt();
players = players/18-1;
//------------------------------------------------------------
//Creating necessary arrays
//------------------------------------------------------------
}
}
EDIT: I must use an array for each player and I am not allowed to use ArrayLists. At this point it looks like I will be using an array of arrays as suggested by some in the comments. Didn't know this was a thing (obviously I'm very noob).
Well you can use a HashMap to store your arrays. Or if you don't care about using strings to get to the array just use 2D Arrays like this:
int[][] players = new int[playerCount][18];
If you then use for example player 2 and want to see hole 12, you'd call players[1][11]
You should not go that way.
Instead create a class named Player to hold each player properties, then create a list of players: List<Player> players = new ArrayList<>();
Add each new player to that list.
I have a simple educational kids game with 7 questions. One imageView and four buttons for each question, the user must match the correct answer(button) with what is shown in the image view. I want the images(questions) to be random every game but never repeat a question during a game until all 7 have been asked. I am only using 3 images as of now just to get it working.
Option 1
int[] res = {R.drawable.img1, R.drawable.img2, R.drawable.img3};
Method
private void randomImage() {
Random rand = new Random();
int rndInt = rand.nextInt(res .length);
imgView.setImageDrawable(getResources().getDrawable(res[rndInt]));
}
Option 2
private ArrayList<Integer> res1 = new ArrayList<Integer>();
res1.add(R.drawable.img1);
res1.add(R.drawable.img2);
res1.add(R.drawable.img3);
Method
private void randomImage1() {
Collections.shuffle(res1);
for(int i=0;i<res1.size();i++){
imgView.setImageResource(res1.get(i));
}
}
Both of these work for randomizing, but I am having a little trouble figuring out how to check if an image has already appeared and to correct it if it had.
In fact I'm not really quite sure where to start. Any help would be appreciated.
If you dont want to see repeated items from array then use shuffleArray() like this example and for a list use shuffle(list) like this example2
I want to test this method:ArrayList<File> songs;
public void playRandomSong()
{
Random random = new Random();
int iNextSong = random.nextInt(songs.size());
File songToPlay = songs.get(iNextSong);
if (mediaPlayer != null && mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer = new MediaPlayerImpl(songToPlay, new WhenDone());
mediaPlayer.play();
currentSong = songToPlay;
}
I'm thinking in this way: Run the method multiple times and see if it returns one of the elements more than once. But how would I write that in code?
Random does not guarantee that it will not return the same value twice...
So you can not test "see if it returns one of the elements more than once"
If you need that you will have to implement a Set around the Random, but be aware of the Birthday paradox...
I think you have 2 options:
1 : You may try to seed your Random, so you can predict the sequence...
2 : Remove the Random and make use of the [Collections.shuffle][1] to shuffle you arrayList
With Option 1 you will have to change the signature of your method.
With Option 2 you will also play every song once.
Instead of creating a RNG in your method
public void playRandomSong() {
Random random = new Random();
...
}
you should pass the source of randomness in (this is called dependency injection)
public void playRandomSong(Random random) {
...
}
and then you can generate a Random instance with a known seed in your unit test to get repeatable but typical results.
public void testPlayRandomSong() {
Random random = new Random(0xd5021e90339050ab);
// Test that 1000 runs plays each song roughly the right number of times.
...
}
I see another problem in your code: if you want to play songs in random order you are doing that in wrong way. This algorithm should not repeat song until all songs in list are played. To achieve that there is an algorithm called Knuth shuffling. You can take it from Collections class: java.util.Collections#shuffle.
Here is an article on randomness testing that you might find useful:
http://beust.com/weblog/2012/02/20/various-ways-to-get-randomness-wrong/
I've coded a simple quiz game for Android, and currently Im having troubles with making questions not appear after they've been shown, i.o. I dont want it to ask me the same question twice..
This is the method Im using
private void QBegin() {
/*
* Gets a random question
*/
question = (TextView) findViewById(R.id.question);
String[] types = { "Question one",
"Question two",
"Question three",
"Question four",
"Question five"};
Random random = new Random();
int qType = random.nextInt(types.length);
question.setText(types[qType]);
getAnswers(qType); //gets four answers
}
Im not sure if this will work but, what if I add something like
Edit : Doesn't work..
int i = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(qType);
i++;
if(list.contains(qType) && i != types.length + 1){
return;
} else {
answerCounter.setText("Hit the bricks pal, you're done..");
}
Edit 2: Got told to add something like this, but I have NO IDEA what I should be doing with this now..
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(types.length);
Collections.shuffle(list);
if(!list.contains(qType)){
// help please, as I have no idea on what I should be doing!
}
The simplest approach would be to generate an ArrayList of all the possible numbers you want to use, the shuffle them with Collection.shuffle. Then just iterate over the list.
EDIT: Your question is really unclear now, given that you've said you don't want the questions in a random order... whereas your sample code appears to be trying to present the questions in a random order. Anyway... here's what I was suggesting:
List<Integer> indexes = new ArrayList<Integer>();
for (int i = 0; i < types.length; i++) {
indexes.add(i);
}
Collections.shuffle(indexes);
for (Integer index : indexes) {
question.setText(types[index]);
getAnswers(index);
// Now do something else? It's unclear...
}
Simple algorithm below:
You need generate value from 0 to N without repeatings.
Define an array with those elements [0..N] (array[n])
Generate random number in interval [0..N] (rand)
Choose in array element, where generated value is index (array[rand])
Swap these element with the last in array (swap array[rand] <-> array[N])
Next time you generate index in [0..N-1] so in that case previously generated element won't be selected.
my homework is this if more context is needed - I would explain it but it is pretty long to explain and the text files are provided on the site if people need to look at them: http://www.cis.upenn.edu/~cis110/hw/hw06/index.html
Right now I am on Step 2 and stuck on randomly choosing from the three items associated with the treasure class, checking to see if they start with "tc". I can extract the treasure class from the monster.txt file and I have the monster. This is my method for finding the treasure class:
public static void getTreasureClass(Monster monGet)
throws FileNotFoundException{
Random rand = new Random();
String tc=monGet.getTreasureClass();
Scanner file=new Scanner(new File ("TreasureClassEx.txt"));
System.out.println(tc);
while(!file.next().equals(tc)){
file.next();
}
tc=file.next();
if (tc.startsWith("tc:")){
}
else {
System.out.println("test");
}
}
It is extremely incomplete, but I would appreciate some tips on where to go next in terms of randomly choosing from the three items, or if my code is bad. Thanks in advance!
So a 'Hell_Bovine' has a Treasure Class of "tc:Cow_(H)".
So you're looking for this line in TreasureClassEx.txt
tc:Cow_(H) tc:Act_5_(H)_Equip_B tc:armo3 tc:armo3
Then you'll choose one of the three options at random.
And you'll keep reading the TreasureClassEx, finding the right line, and making a random choice for as long as the "treasure class" that you're looking for starts with "tc:".
For example, for "tc:Cow_(H)" you might choose "tc:armo3". For "tc:armo3", you might choose "Quilted_Armor". And then you would stop there.
At least that's how I'm reading the instructions. ;->
Makes sure that you import the things that I add, because you dont show imports i will not add them
public static void getTreasureClass(Monster monGet)
throws FileNotFoundException{
Random rand = new Random();
String tc=monGet.getTreasureClass();
Scanner file=new Scanner(new File ("TreasureClassEx.txt"));
System.out.println(tc);
List<String> list = new LinkedList<String>();
while(!file.next().equals(tc)){
file.next();
}
tc=file.next();
if (tc.startsWith("tc:")){
list.add(tc);
}
String treasure = list.get(rand.nextInt(list.size()));
else {
System.out.println("test");
}
}
So in this I saved the example in the String value 'treasure'
I dont feel good helping you with your homework -_-