How to add array list with Doubles - java

My assignment asks for me to add items to a shopping cart, asking the user for input. We are to use the add method but I keep getting an error. I have tried this for days, I have also searched the web and can't find an answer I understand.
List<Double> shoppingCart = new ArrayList<Double>();
shoppingCart.add(" ");
double shoppingCartItem;
shoppingCartItem = numberReader.nextDouble();
for (int counter = 0; counter <shoppingCart.size(); counter++) {
System.out.print("Item");
}
Any help would be greatly appreciated. Also, I am extremely new to java.
I realized what I was trying to do may not have been clear. This is how the completed program should look. I have been working on this for days. Any direction would be so appreciated. I am at a lost, everything I've done has made this worst.
![enter image1

The add(obj) function will add the given object to the list. So you should add your double variable to it. You don't need to add an 'empty' element beforehand (which is what I assume you were tying to do with the empty string?)
E.g
ArrayList<Double> shoppingCart = new ArrayList<Double>();
double shoppingCartItem;
shoppingCartItem = numberReader.nextDouble();
shoppingCart.add(shoppingCartItem);
for (int counter = 0; counter <shoppingCart.size(); counter++) {
System.out.print("Item");
}
Although it might be intimidating at first, its always a good idea to have a read of the docs when working with Classes and functions you arn't familiar with. For example here is information about the add() method.
And I'm guessing you'll probably want to use the retrieve the doubles in your list at some point, so have a read of the get() method.

Related

Multiplication Field in Java / SceneBuilder

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!

A counter that increases and decreases depending on other elements

Im trying to make a PlantsVSZombies game. The player has initially 50 suns in order to buy plants. I want to make a counter which decreases whenever I buy plants but also increases continously if I have sunflowers present. Any ideas how I could do it? And thank you.
In pseudocode:
int counter = 50;
if(....)
...
counter--;
else if (....)
...
counter++;
It would be easier for us if you displayed what code you have tried and what issues you encountered.
For the next time, try to add some information about your classes and how you are planning to write all your code. For this question and with this information you can try to just manage that with one Integer value:
int suns = 50;
public sunsCounter(bool increase){
if(increase){
this.suns +=1
}else{
this.suns -=1
}
I'ts just an idea and it's so basic, obviously, you have to create some classes to manage that and operate with this class objects.

Trying to call a number from another class and display it via jlabel

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

I would like the Arrays to remember it all

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

Java Random: Seeding Problem

was wondering if you could help me out:
I have a method called initializeAll:
public final void initializeAll() {
//other stuff........
rand = new Random(353);
}
So I run the project and a GUI pops up, and some operations are carried out. When I press the "reset" button in my GUI, intializeAll is called again on the same class object. However, the operations that are carried out now are not the same as before, although they should be, since both times, a seed of 353 is being used on the newly created Random object. Why this difference? Am I doing something wrong?
EDIT: sorry, its not "some operations are carried out". its that some initialization of agent population takes place. and each time, the initialization is different, although the same seed is used.
private static int [][] initializePop(Random rand) {
int[][] temp = new int[ROWS][COLS];
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
temp[row][col] = rand.nextInt(12) - 5;
}
}
return temp;
}
SOLUTION:
sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. i'm redesigning the code now. so thanks again, and sorry for wasting your time.
Am I doing something wrong?
Yes, it seems so. The Random(long) should reset the seed to the provided value. What ever the error is, it will be impossible for us to help you without an SSCCE or at least more code.
Random rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
Output:
7
5
5
7
5
5
sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. so thanks again, and sorry for wasting your time.

Categories

Resources