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!
Related
I am using Anylogic to develop a humanitarian logistic supply chain. This model needs to send lorries from Armies stations to warehouses
from which to pick item to support people affected by eartquake and go to epicenter to drop them. This model have to select for each
lorries, nearest warehouse which have availabilty of items in it. For example, if the nearest warehouse has not availablity, lorries have
to select the second nearest warehouse which have availablity and go on it to pick item and go at the epicenter.
I realize this state chart in which I defined an algoyrthm that have to choose the nearest warehouse which have availabilty of items in it, as follow:
List <Magazzini> subsetlist = findAll(main.magazzinis, w->w.availabilty>0);
// I select just warehouses with availablity
List <Magazzini> sortmag = new ArrayList<>();
sortmag = subsetlist;
for (Warehouses m : subsetlist)
{
distance.add(distanceTo(m));
sortmag = sortAscending(sortmag, p-> p.distanceTo(m)); //anylogic function which sort agent according a condition (distances
// from lorry in that case)
}
moveTo(sortmag.get(0)); //move towards the first one warehouse of the sorting made in the for cycle
System.out.println(sortmag); // just to print the result
sortmag = new ArrayList<>();
Anyway, this algorythm doesn't work for all lorries which read it on the state chart (in the state named "at_warehouse"), but just for
the first one. Subsequently, all lorries "read" the same result elaborated for the first one.
How can I fix it? Please, answer just if you know Anylogic software and don't close this post. For any further infos, please answer and
I'll give you that. I need to fix this problem for my thesis work. Thank you so much.
PS: I've uploaded also a pic in which you can see lorry which starts from Salerno and go to Bari and not towards Naples, where there is a warehouse with availabilty.
enter image description here
Maybe you could first set the distance value in a loop and then sort the Arraylist,
in this case you also have to create a property called distance in Magazzini
like so
for(Magazzini m: subsetList){
m.distance = distanceTo(m);
}
sortmag = sortAscending(subsetList, p-> p.distance);
Hope this helps
I am VERY NEW to Java. I don't even know if I am asking the correct question, however I need help.
So I am trying to set an object's variables depending on what the user inputs. However, I am trying to make my code more efficient (by re-using methods) and this is my problem:
if (Store.product1.productName.equals("")){
Store.product1.setProductName(inputProduct);
Store.product1.setProductDemandRate(productDR);
Store.product1.setProductSetupCost(productSC);
Store.product1.setProductUnitCost(productUC);
Store.product1.setProductInventoryCost(productIC);
Store.product1.setProductSellingCost(productSP);
System.out.println(System.lineSeparator() + "Product " + inputWithCap + " Added Successfully. Returning to Main-Menu" + System.lineSeparator());
displayMenu();
}
So if I have 5 products, does that really mean I have to have that large amount of code 5 times? I can't think of a method that would allow me to just shove in some parameters and it'll do the rest :(
Any help would be GREATLY appreciated!
NB: I'm not allowed to use arrays :(
No you don't need to repeat your code several times. Each time you need a new product you should create one and then add it to the store once the values are set:
Product product = new Product(name);
product.setDemandRate(demandRate);
...
store.add(product);
The store needs to be able to take as many new products as you need. There are plenty of structures other than arrays that you can use to store them.
I have a table written in GWT from a List list. What i want it is to obtain the sum of a certain group of elements.
The problem with this, it is that the value I want to do the sum with its calculated, and thus not obtainable unless you calculate it before generating the List.
I was wondering if it was somehow possible to achieve this through DOM manipulation. And if so, how?.
I will show you an example:
DataA DataB DataC DataD
---------------------------------
aaaaa bbbbb ccccc 12
aaaa1 bbbb1 cccc1 15
aaa11 bbb11 ccc11 17
I want to get the sum of "DataD" column, but i dont know how can i do it.
Thank you in advance for your time,
Kind regards,
Elaborate: DataD column value it is calculated and the value comes from another system and its placed into the table through a third party program; thus i cannot get its value and use it into a sum to get the value i want.
You should be able to add some event handler to the table's widget so that whenever data is added/changed in the widget, you adjust the total. Please give more information about what widgets you are using to represent the table.
EDIT:
now that we know you are using an HTMLLayoutContainer, I assume DataD is being poopulated at a place beyond your controll in code. What you can do is add event handlers to handle the add remove etc events. For example, you could do something like below:
//Your container
HtmlLayoutContainer c = new HtmlLayoutContainer(templates.getTemplate());
c.addAddHandler(new AddEvent.AddHandler() {
#Override
public void onAdd(AddEvent event) {
//Do proper exception handling, check if it is the right widget for dataD, do the needed calculations etc
sum += Double.parseDouble(((HTML)event.getWidget()).getHTML());
}
});
c.addRemoveHandler(new RemoveEvent.RemoveHandler() {
#Override
public void onRemove(RemoveEvent event) {
//handle all conditions like in onAdd in AddHandler above
sum -= Double.parseDouble(((HTML)event.getWidget()).getHTML());
}
});
You can look into the API to see what exactl events match your needs best (http://dev.sencha.com/deploy/gxt-3.0.0/javadoc/gxt/com/sencha/gxt/widget/core/client/container/HtmlLayoutContainer.html)
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
This is about my assignment so I would appreciate generic answers with explanation.
I have a for-loop which I have to make for an online ordering system. The for-loop and ordering all works fine but if the same item is put in twice, then it forgets the previous order for the same item and only remembers the latest one. I am required to use simple arrays and for-loops so I would appreciate if the solution/help was also of this basic level.
My code looks something like this (NOTE: The following is just an example of what part of the loop looks like--this is not a complete program):
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
int price = quantity[i] + itemcode;
}
}
To explain further, this loop and the if statement work perfectly if a certain item is only ordered once. But if the user enters, say, an order for a computer once and then after 3 more orders, orders another computer, then the output does not add the previous order in the new order but only remembers the latest one.
I would appreciate any work around suggested for this but again, since this is for my studies, I would appreciate explanations rather than direct solutions.
Please ask me questions in case this is not clear.
"Forgets" suggests that you are overwriting something in your code rather than, say, just incrementing. Go through your code, see what parts of it gets reset when you place a new order. For instance, if you are doing
quantity[1] = getNumberFromUser("How many apples?");
then this would obviously erase the old value each time. If you want to merely increment the number of apples, do something like
quantity[1] += getNumberFromUser("How many apples?");
Another general advice is to use print statements to debug your code. That way you can see for yourself what really happens. Learning to use a real debugger would also be of great benefit.
if you have two or more typres of products and want to calculate the price for all the orders together then you can try the following code,, i think thats very simple,,
int price=0;
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
price += quantity[i] + itemcode; //use the previous value of price
}
}
or else if you want to have history for each product separately then you have to try the same with a array of price for each product type..
If you cant get the answer then comment here,,