Searching through text file and randomly choosing? - java

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 -_-

Related

Print random key followed by specific value? [duplicate]

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())));
}
}
}

How to dynamically create a specified number of arrays with different names in Java

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.

Java use a piece of code from a text file

I am currently trying to figure something out. For my world editor I want my program to read a text file and use its content as code material. I've already made a decent file reader but now I've got a problem. In the console I am getting the right output, the file has only one line that says:
this.makeGrass(new Vector3f(0, 1, 2));
this is actually part of a code that tells my program to render a specific object to the scene, in this case it's a grass model. However instead of just printing this information to the console with
System.out.println(aryLines[i]);
I want to be able to use the information stored on the .txt file so I can actually add it to my rendering code. The entire method that prints the lines on the text file to the console is:
public void TextOutput()
{
String file_name = "C:/Text.txt";
try
{
StoreCoords file = new StoreCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
// !! How to use the information as part of my code ??
}
} catch(IOException e)
{
System.out.println(e.getMessage());
}
}
I hope you understand what I want: The content of my text file is a piece of code that I want to use further instead of having it just print to the console, I'm sure this is possible but I wouldn' know how.
As Java is a compiled language, you'd have to recompile at runtime and I am not sure that is even possible. If I were you, I'd hardcode in my own commands. You want to call a function called makeGrass, hardcode it in. Maybe in your text file you can have this:
makeGrass:0,1,2
Then have this right after the println:
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
ArgArray = Arguments.split(",");
this.makeGrass(new Vector3f(Double.parseDouble(ArgArray[0]), Double.parseDouble(ArgArray[1]), Double.parseDouble(ArgArray[2])));
}
I'm going to leave my answer like this, assuming you are an experienced programmer. If I am wrong feel free to ask and I will explain it to you. I can also explain how to modify it to add different commands if you want.
Also, this is rather unsafe because if the input is in the wrong format it will crash the app. If you plan on letting users edit the file, then I can show you how to add on safeties.
Hope this helped,
Joseph Meadows
Okay, thanks to Joseph Meadows for the hint, I'm doing the following thing, right after the println statement I've added the code provided by him. To make ArgArray work I had to put String[] before it and also I had to create a new constructor in my Vector3f class to match the Double.parseDouble thingy..
public void TextOutput()
{
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
StoreCoords file = new StoreCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
String[] ArgArray = Arguments.split(",");
this.makeGrass(new Vector3f(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2])));
}
}
} catch(IOException e)
{
System.out.println(e.getMessage());
}
}
my original Vector3f constructor is:
public Vector3f(float x, float y, float z)
{
this.m_x = x;
this.m_y = y;
this.m_z = z;
}
and to make the code in the TextOutput method work I've added another constructor right below the original one..
public Vector3f(double parseDouble, double parseDouble2, double parseDouble3) {
this.m_x = (float) parseDouble;
this.m_y = (float) parseDouble2;
this.m_z = (float) parseDouble3;
}
Now everything works great, the console gives me the apropriate statement
makeGrass:0,1,2
and the rendering system creates the grass model at the apropriate coordinates, the only thing I want to change now is that I don't have to add an additional constructor to the Vector3f class, I'm sure I'll figure that out too.
In the picture provided in this link you can see exactly what's going on:
http://www.pic-upload.de/view-27720774/makeGrassEx.png.html
As you can see, the content of the text file is printed out in the console (the numbers below is the fps counter) and the coordinates provided by the text file are interpreted correctly, two grass models being displayed at the respective coordinates which is exactly what I wanted!
Thanks again for your help Joseph Meadows, this is exactly what I was looking for!
I am not sure if you solved this yet, but you did not need the second constructor. I was unsure of the data type you were using for the coordinates, and I assumed you use doubles because that is what I have grown accustomed to using.
In actuality, all types can be parsed from a string. Look here:
this.makeGrass(new Vector3f(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2])));
This right now is turning the string into a double. That is what
Double.parseDouble();
does.
It looks like you are using floats though, so you can always just use the float parsing method:
Float.parseFloat("String");
That would result with this:
this.makeGrass(new Vector3f(Float.parseFloat(ArgArray[0]),
Float.parseFloat(ArgArray[1]),
Float.parseFloat(ArgArray[2])));
Sorry for the late response, and you are surely welcome for the help. I just love being useful!

Need help randomizing images and not repeat throughout activity

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

Printing individual parts of an array in a Java Gui app

OK, so I created a console app that, among other things, takes an array of numbers and prints them out one by one, line by line. Now, I have to take the class that I created for that console app, and pop it into a separate GUI app we're creating. I have all of the other methods working fine, but for the life of me I cannot get the array method to print out correctly. It just gives me the last number I typed into the text field. I'm hoping someone can give me a nudge to help me figure this part out so I can move along, and get to the whole SpringLayout stuff, (the main part of the new assignment) I am limited in what I can show you here because this is a current assignment, so I will have to stick to this stuff as specifically as I can. And please, don't just post the code as an answer, (because then I can't use it), thanks.
Here's what I had for my original project for the array method:
int [] getArray(int x)
{
breakUpNum(x);
return numAry;
}
From there, inside my new class I have this, in an attempt to get it to print:
private class ButtonTest implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
Lab1 tester = new Lab1();
int[] test4 = tester.getArray(num);
for(int i = 0; i < test4.length; i ++)
{
crossTest.getArrCross.setText("" + test4[i]);
}
}
}
Any help pointing me in the right direction would be greatly appreciated, thanks!
setText does just that, sets the text you pass to as the current text content, it does not append it.
If you were to use JTextArea, you could use it's append method...however, for a JTextField you need to have a different approach.
Now you could use getArrCross.setText(getArrCross.getText() + test4[i])...but to quite frank, that's rather inefficient, as each call to setText is going to stage a paint event...
StringBuilder sb = new StringBuilder(128);
for(int i = 0; i < test4.length; i ++)
{
sb.append(test4[i]);
}
crossTest.getArrCross.setText(sb.toString());
Now, if you want to separate each element, you need to add
if (sb.length() > 0) {
sb.append(", ");
}
Before sb.append(test4[i]);
The last bit of actionPerformed in the for loop isn't working right. setText replaces the current text with its argument, and it doesn't seem like you want to do that. To fix it, replace the line in the for loop with this:
crossTest.getArrCross.setText(crossTest.getArrCross.getText() + test4[i]);

Categories