Please see ifmy logic is correct i do not know how to implement what i am trying to do. I am a beginner in java.
Game is a class which stores the Name and the Steps of that user after the game is complete.
[ First Method ]
private game[] gameArray = new game[10];
for(int i = 0; i <gameArray.length;i++){
gameArray[i].setName(nameTxt.getText());
gameArray[i].setpSteps(stepsCount);
}
By Clicking History Button they will get the previous 10 people's name and steps.
JOptionPane.showMessageDialog(null,
"Player's Name No. of Steps"+
"\n"+gameArray[i].toString());
-The Problem:
1) This code limits to only previous 10 results is there anyway i can get all the previous results
2) This code is not working!
[ Second Method - This is also not working! ]
private game[] gameArray = new game[10];
// Storing the name of player[i]
gameArray[i].setName(nameTxt.getName());
// Storing the number of steps player[i] took.
gameArray[i].setpSteps(stepsCount);
//Displaying previous 10 players name and steps
JOptionPane.showMessageDialog(null,
"Player's Name No. of Steps"+
"\n"+gameArray[i].toString());
Some points:
you can't directly convert an array to a String through toString() because it isn't supported in Java, you should use Arrays.toString(..)
Java arrays have static size, if you want to store the whole history you will need a dynamic data structure as an ArrayList<Game> or a LinkedList<Game>
name of classes should be capitalized (Game, not game)
without knowing the internals of your Game class it's impossible to tell what is not working and why it is not working, we don't even know what it is supposed to do exactly
Related
I'm a java Beginner and I've created a program where you can type in some food in a TableView and the details of the respective food you can type in a GripPane. One of the Details you have to type in is the quantity of the food, and another is the Calories per piece. Now I would like to create a button and a field. Or Maybe just a field that shows all calories of the food in the Table view. So it should multiplicate the quantity with the calories, for every food and add them all together. For a Total of Calories. Now I have no idea how to do that. Could somebody help me with step-by-step instructions? Not sure if it makes sense to add some code to the program. By the way, I use Eclipse on Windows and SceneBuilder. Thanks for every help.
Cheers Blarg
The first piece of advice from my side would be to try writing some code on your own! That way you learn and you wouldn't need to copy and paste somebody else's code.
And secondly, this is how I would approach it:
Create the fields as you described below in the Scene Builder and give them all id (names) so that we can access them in our controller (I am supposing you know how that works).
Add a button so that the user can click to perform the calculation
When the button is clicked, you can get all the information from each TextBox and create a Food Object with all the information. Performing the calculation is a rather simple task that can be done by converting the data received from the TextBoxes into numbers and multiplying
public void addFoodItemIntoTable()
{
...
String quantityOfFoodStr = quantityTextBox.getText();
int quantityOfFood = Integer.parseInt(quantityOfFoodStr);
String caloriesOfFoodStr = caloriesTextBox.getText();
double caloriesOfFood = Double.parseDouble(caloriesOfFoodStr);
double total = quantityOfFood * caloriesOfFood;
...
}
After adding all the elements in your TableView (Check this). You can easily get the total of the field by iterating all the elements of your table and adding them into a variable.
Example:
double total = 0;
for(Food currentFood : foodTable.getItems())
{
total = total + currentFood.getTotalCalculation(); // The naming should not be correct... Change it to whatever you find suitable
}
Good luck!
I'm not actually sure how to ask this question because its very confusing. I have a java app that has a MVC structure, which gets data from a database. I retrieve String ArrayList of data from a JDBC query. It contains information about Competitors in a race (eg: Name, Race_no, Start_Time, Swim_Time, Bike_Time, Finish_Time etc). The list size will vary week to week depending on the number of the competitors who raced that week. I have no problem getting the data from the database, but when I pass the information to the controller to pass to the view, I am having trouble assigning the data to a JLabel. So far the data is sent as one large array so I need to somehow split the array up in blocks of 12 (which is how many JLabels are required to be set for each competitor). I then set each of those 12 JLabels into its own JPanel ArrayList - then dynmically add to one JPanel for printing. My question is, how do I split the ArrayList to get the first 12, then the second lot of 12, etc.. I have tried doing a nested loop and set the size to 12, but of course that only gets the first 12 everytime. Maybe I need to store the data from the JDBC result set as something else.. I really need some guidance on this as have been stuck for days.
nb: I had this working as one large method in the data handler class, where I would use the while(rs.next()) to do all the work, but because of the MVC structure, I need to break the code up: This is the desired outcome:
EDIT:
I have implement this code which give me the desired output, but now having trouble assigning the JLabel variables with the data in the [j] loop:
<pre>
public void getRaceLabels()
{
ArrayList<String[]> raceLabels = dh.getRaceTimeLabels();
//System.out.println(raceLabels);
for (int i = 0; i < raceLabels.size(); i++)
{
String[] element = (String[]) raceLabels.get(i);
//System.out.println(element);
for (int j = 0; j < element.length; j++)
{
System.out.print(element[j]+" ,");
}
System.out.println("break");
}
</pre>
Create yourself a POJO which represents the basic information you need for a single record.
When loading the data from the database, load this data into the POJO.
Now, for each panel, you just need to pass it a single object, meaning you can now get away with using a simple iterator instead
To begin, I am a very beginner in Java. I have looked at many different posts regarding similar problems but still could not seem to solve my problem.
String[] names = {"elephant, tiger, monkey, baboon, barbeque, giraffe, simple, zebra, porcupine, aardvark"};
Random rand = new Random();
name = names[rand.nextInt(names.length)];
return name;
From this snippet of code I am trying to have Java select a single word from the string array, such as just selecting the word "Tiger". This is for a Hangman game and this is trying to select the word that the user is trying to solve. Yes, this is for a school assignment so teaching and not just giving code would be GREATLY appreciated.
The main problem I am running into is that when the code is going to grab the word that I want to use, it is selecting the entire String array and is trying to have the user solve the entire thing, when I just want one word from it.
If more code is needed I can supply it, just remember I am a very very beginner in programming so the code is not very good.
The problem is how you are initializing your string array:
String[] names = {"elephant, tiger, monkey, baboon, barbeque, giraffe, simple, zebra, porcupine, aardvark"}
This is a string array with one string that is "elephant, tiger,...
You want to do this:
String[] names = {"elephant", "tiger", "monkey"...
Notice the extra quotation marks.
String[] names = {"elephant", "tiger", "monkey", "baboon", "barbeque",
"giraffe", "simple", "zebra", "porcupine", "aardvark"};
Use this, hope you understood why. You have assigned the whole thing as a single element before.
Your array as of right now is one long string. If you were to call names[0], you would get elephant, tiger, monkey, baboon, barbeque, giraffe, simple, zebra, porcupine, aardvark back.
You need to initialize your array with individual strings such as elephant, tiger, monkey, etc.
I am trying to write code for a command like game of Farkle (greed). This is an Intro to computer science class. In a nutshell, you roll 6 die, and scores are based off of what you roll. Then you are required to remove the die that were used -> display score from that roll -> display total score -> ask if they would like to roll again. First player to a score determined by the user is the winner.
I have a bunch of code written for the model, and I am working on the view. I am struggling with the view, which makes it harder to advance on my model code. We are required to use the Die and Player classes (we were given those). I use the Die quickly, not quite sure how to apply the Player class.
When I try to run my command line, I am getting out of bounds errors on my rollCheck() array and other issues in my model that were not coming up when I simply was testing in main. I apologize for the amount of code posted, but I figure seeing everything makes it easier to solve (goes without saying really).
If anyone can give me pushes in the right direction to solving and making my program work, that would be great! Thank you.
Without being able to run the program to be sure its hard to be certain (I need the top of GreedGame) but i'd be fairly confident its the following:
in rollDie die is set to an array of ints on size remainingDie
this.die = new int [remainingDie];
later, within rollCheck the contents of the die array up to and including remainingDie, going over the array by 1
for (int i = 0; i <= remainingDie; i++) { // Count up quantity of die (6 set to remaining die)
if (die[i] == 1) {
this.numFreq[0] += 1;
}
....
....
}
So in short I believe i <= remainingDie; should be i < remainingDie; because an array with 6 entries has "boxes" 0,1,2,3,4,5
Hello there im having a little problem here, i am trying to call a random number generated in another class and display it via jlabel in 2nd class (jform) and i am sort of lost. number generating is double.
code
GaussianGenerator num = new GaussianGenerator();//calling another class
CriminalDetails()
{
initComponents();
double number = 0;
num.GaussianGenerator(number);
CriminalID.setText(Double.toString(number));//CriminalID jfield
}
The number im getting on jfield is the 0 initialized in "double number" but i want to get number generated in GaussianGenerator class.
Thank you for having a look and your time, help appreciated.
num is an instance of the number generator. You should be setting the value of number by calling a method on the instance of the number generator object and assigning it to number. Like this (I am not familiar with your other class):
GaussianGenerator num = new GaussianGenerator();//calling another class
CriminalDetails()
{
initComponents();
double number = 0;
number = num.getNextValue();
CriminalID.setText(Double.toString(number));//CriminalID jfield
}
Or is GaussianGenerator is also the name of the method? Bad idea from a design standpoint. Rather than passing it to the method as a paremeter, the method should just return the generated value:
numer = num.GaussianGenerator();
In Java you can't pass a primitive by reference if that is what you are trying to do. You can do this with objects (e.g. Double), however, but that is bad design since a double will suffice. You should also read a good tutorial on Java coding conventions so you can learn how to properly name and capitalize methods. So you would see that this is better coding:
number = num.getNextValue();