I am currently working on a small program that allows the ordering of items and the total cost to be stored in a JavaDB.
I have managed to successfully store integer values into the database but the cost amount for the items are not correct. It seems like when the check box is selected it is counting that as a value on top of the set value. Would anyone be able to take a look and see where I am going wrong?
Any help would be greatly appreciated!
Screenshot:
http://i.imgur.com/ad41ooG.png
OK - I think I can see your problem. Reducing the code a bit further, you have:
int fanta = 1;
int crisps = 1;
int beer = 2;
int wine = 3;
int water = 0;
...
if(btnFanta.isSelected()) fanta++;
if(btnCrisps.isSelected()) crisps++;
if(btnBeer.isSelected()) beer++;
if(btnWine.isSelected()) wine++;
if(btnWater.isSelected()) water++;
rs.updateInt("TotalCost", fanta + crisps + beer + wine + water);
So, if nothing is selected, you're adding up all the values: 1 + 1 + 2 + 3 + 0 = 7, and inserting that. If Fanta is selected, you first increment the value of fanta, making it 2, then add it to the values of all the other snacks: 2 + 1 + 2 + 3 + 0 = 8, which is what you're seeing in the database when you select Fanta.
Hopefully that makes sense, and I'm guessing that's not what you want. I'd suggest that one solution would be to add a new variable, say, totalCost, and add the values to that if the relevant checkbox is selected, so, you'd end up with something like:
int fanta = 1;
int crisps = 1;
...
int totalCost = 0;
...
if(btnFanta.isSelected()) totalCost += fanta;
if(btnCrisps.isSelected()) totalCost += crisps;
...
rs.updateInt("TotalCost", totalCost);
(In case you're not familiar with the += syntax, it's the same as saying totalCost = totalCost + fanta, i.e. you're adding fanta to whatever totalCost was previously.)
Related
My project is a simple agent based simulation that models the spread of disease. The simulation consists of agents and map, the classes that belong to agents are: Civil, Medic and Animal. Currently I'm trying to fill the map according to the size of populations: noMedics, noCivils, noAnimals and amount of healthy, ill, and immune agents that should add up to total population of both humans and animals.
The way that health status of an agent is determined is simple - random.nextInt(3), 0 being healthy, 1 ill and 2 immune. The way that I would usually fill the map with one of the agent class is as follows:
for (int i = 0; i < noAnimals; i++) {
IAgent animal = new Animal(map, rnd.nextInt(3), 2, 3);
agentList.add(animal);
}
However the issue arises whenever I would try to implement the remaining parameters of simulation that is: noHealthy, noImmune, noIll. I can't seem to find a loop or condition that would fullfill my need which is to "fairly" fill the map with all agents of in the given createAgents() method. Create agents takes 6 parameters: noHealthy, noImmune, noIll, noAnimals, noCivil, noMedics.
I've tried few things already but the one that compiles and runs correctly so far is as follows: I'm creating a loop that runs from currNoImmune until noImmune from parameters and whenever a condition sumForImmune < halfNoAnimals && currNoImmune <= noImmune is fulfilled it adds an animal to the simulation and increments sumForImmune and currNoImmune once. The reverse check is done for civlians sumForImmune >= halfNoAnimals && currNoImmune <= noImmune incrementing the same variables and adding a civil to the simulation. Here is the code for method I've described:
while (sumForImmune <= noImmune) {
if (sumForImmune < halfNoAnimals && currNoImmune <= noImmune) {
agentList.add(new Animal(map, 2, 0, 2));
sumForImmune++;
currNoImmune++;
}
if (sumForImmune >= halfNoAnimals && currNoImmune <= noImmune) {
agentList.add(new Civil(map, 2, 0, 2));
sumForImmune++;
currNoImmune++;
}
}
Then there are two loops that run until noIll and noHealthy and that's how agents are created so far. It works however not quite how I hoped it would. Numbers that are passed as arugments to createAgents() aren't being reflected on the map for all possible inputs. I realize that this task is beyond my capabilities since I've spend a good amount of time trying to figure it out, despite that I would still love to understand how it's done and how it can be achieved.
What I mean by fairly is as close to 50:50 as possible - whenever user inputs an uneven number of 3 immune, 1 animal and 2 civil agents there should be 2 immune civilians and 1 immune animal. Same logic shoud be extended to the missing parameters that is healthy and ill agents.
Edit:
What I mean by that mess written above is that I need an algorithm to place agents according to the ratios determined by noHealthy:noIll:noImmune for both population of Civilians (noCivils) and population of Animals (noAnimals). Taking into account that Medics are already immune so noImmune should shrink by the number of Medics present in the simulation.
Edit2:
I've played around with the maths a bit and this is what I managed to get but there is still issue with 1:1:1 ratios as they don't give expected results for given population sizes. One more thing is this doesn't account for medics yet, just so it doesn't mess the ratios and makes the logic a bit easier.
void createAgents(int noAnimals, int noCivil, noIll, noImmune, noHealthy) {
double sumTheRatio = noHealthy + noIll + noImmune;
double animalsPart = noAnimals / sumTheRatio;
double numHealthyAnimals = noHealthy * animalsPart;
double numIllAnimals = noIll * animalsPart;
double numImmuneAnimals = noImmune * animalsPart;
double civilPart = noCivil / sumTheRatio;
double numHealthyCivil = noHealthy * civilPart;
double numIllCivil = noIll * civilPart;
double numImmuneCivil = noImmune * civilPart;
//The only issue is when ratios of agent health states are 1:1:1
//- for example for ratios like 18:18:18 and 26 civilians 28 animals will
// give 27 agents for both animals and civilians (+/- 1 from expected numbers)
//- another example 7:7:7 and 1 civil and 20 animals will give 0 agents
// for civilians and 21 agents for animals (+/- 1 from expected numbers)
//- another example 14:14:14 and 38 civilians and 4 animals will give 39
// agents for civilians and 3 agents for animals (+/- 1 from expected numbers)
System.out.println("Rounded ratio number for animals:"
+ "\n healthy - " + Math.round(numHealthyAnimals)
+ " ill - " + Math.round(numIllAnimals)
+ " immune - " + Math.round(numImmuneAnimals));
System.out.println("Rounded ratio number for civilians:"
+ "\n healthy - " + Math.round(numHealthyCivil)
+ " ill - " + Math.round(numIllCivil)
+ " immune - " + Math.round(numImmuneCivil));
}
Then simply iterating to: Math.round(numHealthyCivil), Math.round(numIllCivil), Math.round(numImmuneCivil) and adding respective agent with each iteration.
Is there a way to adjust this algorithm or perhaps there is a need for different function responsible for agents creation whenever ratios are 1:1:1?
You say that Medics should have an Immune health status. The remaining problem is therefore to assign Civilians and Animals a health status of Healthy, Ill, or Immune such that:
noCivils + noAnimals + noMedics = noHealthy + noIll + noImmune
One way of doing this would be to create a health status array noCivils + noAnimals long and populate it with noHealthy, noIll, and noImmune-noMedics elements of the corresponding type (0, 1, 2). You then randomly shuffle this array and use the values to assign a health status to Civilians and Animals in turn.
Here's some Java code to illustrate:
static void createAgents(int noHealthy, int noImmune, int noIll,
int noAnimals, int noCivil, int noMedics)
{
for (int i=0; i<noMedics; i++) {
// create and add Medic, with health status Immune
}
int remImmune = noImmune - noMedics;
assert noCivil + noAnimals == noHealthy + noIll + remImmune;
int caAgents = noCivil + noAnimals;
Integer[] agentStatus = new Integer[caAgents];
Arrays.fill(agentStatus, 0, noHealthy, 0);
Arrays.fill(agentStatus, noHealthy, noHealthy+noIll, 1);
Arrays.fill(agentStatus, noHealthy+noIll, noHealthy+noIll+remImmune, 2);
Collections.shuffle(Arrays.asList(agentStatus));
int j = 0;
for (int i=0; i<noAnimals; i++, j++) {
// create and add Animal, with health status status[j]
}
for (int i=0; i<noCivil; i++, j++) {
// create and add Civilian, with health status status[j]
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I've tried to make Java code to communicate with the user.
The code is about calculating a pizza price assuming the pizza price is a final int and doesn't change.
The only thing that affects the price is the add-on that the customer wants on the pizza (tomato, mushrooms, cheddar cheese).
I've tried to create code that covers every option the customer picks using 'if' statements,
but I think there is easier way to do it.
(I want the program to calculate the price given only the add-on name.)
For example, the customer picks Mushroom and Tomato so the pizza price will be the pizza price + tomato price + mushroom price.
Is there any easier way to solve it?
Or should I cover every option the customer picks with if/else statements?
public static void main(String[] args){
Scanner s= new Scanner(System.in);
final int pizzaPrice= 12;
int Mushrooms = 2;
int Tomato= 2;
int Corn = 2;
int Olives = 2;
int CheddarCheese=3;
int bulgaritCheese=3;
int yellowCheese= 3;
String cheapAddOns ="Mushrooms , Tomato, Corn, Olives";
String expensiveAddOns = "Cheddar cheese , Bulgarit cheese , Yellow cheese";
System.out.println("Please enter first AddOns(Mushrooms , Tomato , Corn, Olives): ");
cheapAddOns=s.next();
System.out.println("Please enter second AddOns (Cheddar cheese , Bulgarit cheese ,Yellow cheese)");
expensiveAddOns=s.next();
if( cheapAddOns== "Mushrooms" || expensiveAddOns=="Cheddar cheese" ) {
System.out.println("Your Pizza price is: $" + pizzaPrice + Mushrooms + CheddarCheese );
}
else if (cheapAddOns=="Tomato" || expensiveAddOns=="Bulgarit cheese") {
System.out.println("Your Pizza price is: $" +pizzaPrice+ Tomato + bulgaritCheese);
}
}
First of all when you name your variables, don't start with a capital letter
int mushrooms, not int Mushrooms.
Second thing, when you compare Strings == operator will not work. you must use stringName.equals(). In your case it would look like:
cheapAddOns = s.next();
if(cheapAddOns.equals("tomato") || cheapAddOns.equals("mushrooms") || ...){
//this way you can get one if for all cheap addons;
pizzaPrice += 2; //read below to undrstand why i would add price this way
}
And the same check for expensive addons.
What you do when you initiate cheapAddOns and expensiveAddOns is incorrect, I mean that you initiate them with start variable, and next you read them from standard input. Initiate them with no value:
String cheapAddOns;
String expensiveAddOns;
And for this example, you dont have to use final int, better initiate it as an normal integer, and if any statment is true, add to this value. It would look like this:
int pizzaPrice = 12;
int cheapAddonPrice = 2;
int expensiveAddonPrice = 3;
if(anyStatement){
pizzaPrice += 2; //2 for cheap, 3 for expensiv addon
}
System.out.println("Your pizza costs: $" + pizzaPrice)
It works only when all cheap addons cost $2 and all expensive addons cost $3. If each addon has another price, you will need more if statements to calculate price.
But calculate price in as many statements as you want and print it once (until you print only price (without addons list).
You made a lot of simple mistakes here so i think that you just start your programming adventure. Don't learn bad habbits, try to imporove your code with each day.
if all cheap add-ons have the same price, one way could be:
String cheapAddOns = "Mushrooms, Tomato, ...";
int cheapPrices = 2;
System.out.println("Please enter first AddOns(Mushrooms , Tomato , Corn, Olives): ");
String cheap = s.next();
int price = pizzaPrice;
if ( cheapAddOns.indexOf(cheap) >= 0 ) {
price += cheapPrice;
}
then repeat the code using expensiveAddOns.
Note that you will need to consume the CR before calling s.next() to get the user's next input.
I am trying to build a student graph with JLabels
my app does a sql query and returns an int value for each month's number of entries and if doesnt find any it returns 0.
//scale variable is an int
//ene is a return value from another method that runs before
//in case there are no students in january I dont have to graph anything
//so this 'if' doesnt run
Scale = 50;
if (Ene != 0) {
System.out.println(Ene + " ene stdds");
// this prints out 11 ene stdds
double EneBH = 449 * (Ene / Scale);
int EneBHeight = (int) Math.round(EneBH);
int EneBYLocal = 612 - EneBHeight;
EneP.setBounds(76, EneBYLocal, 7, EneBHeight);
EneP.setVisible(true);
} else {
//if the last if didnt run I want to know if it hidd the label
System.out.println("HIDDEN ENE");
EneP.setVisible(false);
}
*Ene P is the very first jlabel for graphing, it looks kida gray and is at the enero zone.
*EneP prints out 11 students but never shows up, doesnt print hidden ene, it just doesnt show up
*EneP will have the same code than the other jlabels if I solve it or you solve it, please
I have found a Solution for My Own Problem
The solution was easy turns out that If you divide Ene (the return variable from a query that saves as an integer value) by the Scale variable which is also an integer it causes java to return 0
So I have discovered this on my own by placing a system.out.print() after every line and printing the values of every variable.
I noticed 11/50 shouldn't return 0, so I changed the scale variable to be a double and still returned 0; but I changed both and now it works just right.
Scale = 50;
if (Ene != 0) {
System.out.println(Ene + " ene stdds");
// this prints out 11 ene stdds
double EneBH = 449 * (Ene / Scale);
int EneBHeight = (int) Math.round(EneBH);
int EneBYLocal = 612 - EneBHeight;
EneP.setBounds(76, EneBYLocal, 7, EneBHeight);
EneP.setVisible(true);
} else {
//if the last if didnt run I want to know if it hidd the label
System.out.println("HIDDEN ENE");
EneP.setVisible(false);
}
enter image description here
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have an assignment that requires me to make the SalesByQtr java program i've gotten most of the program done but I have a couple of problems
Firstly: My total is being displayed as a double which I know I need printf to add a decimal place. The same thing is happening for Average.
Second: My division with the highest sales is saying Division 1 has the highest sales in qtr 1 and it repeats this in each qtr also Division 1 does not have the highest sales
Finally: My assignment requires that in qtrs 2-4 to display the change in sales and I can't figure out how to do that.
Here is the example output my professor is looking for
Example Output (bullet points represent spaces)
Q1:
D1:·1000.00↵
D2:·1700.00↵
D3:·300.00↵
D4:·2000.00↵
D5:·1400.00↵
D6:·500.00↵
Total:·6900.00↵
Average·sales:·1150.00↵
Division·with·highest·sales:4↵
Q2:
D1:·2500.00,·Change:·1500.00↵
D2:·500.00,·Change:·-1200.00↵
D3:·700.00,·Change:·400.00↵
D4:·2500.00,·Change:·500.00↵
D5:·1450.00,·Change:·50.00↵
D6:·1050.00,·Change:·550.00↵
Total:·8700.00,·Change:·1800.00↵
Average·sales:·1450.00↵
Division·with·highest·sales:1↵
Q3:
D1:·3000.00,·Change:·500.00↵
D2:·1000.00,·Change:·500.00↵
D3:·120.00,·Change:·-580.00↵
D4:·2700.00,·Change:·200.00↵
D5:·980.00,·Change:·-470.00↵
D6:·750.00,·Change:·-300.00↵
Total:·8550.00,·Change:·-150.00↵
Average·sales:·1425.00↵
Division·with·highest·sales:1↵
Q4:
D1:·2700.00,·Change:·-300.00↵
D2:·1300.00,·Change:·300.00↵
D3:·155.00,·Change:·35.00↵
D4:·3500.00,·Change:·800.00↵
D5:·1450.00,·Change:·470.00↵
D6:·1023.00,·Change:·273.00↵
Total:·10128.00,·Change:·1578.00
Average·sales:·1688.00
Division·with·highest·sales:4
Here's my code:
My Code
public static void main(String[] args) {
int divs = 6;
int qtrs = 4;
double errorCheck;
double[][] sales = new double[divs][qtrs];
double[] qtrsales = new double[qtrs];
int highestDiv = 0;
int[] highestDivi = new int[qtrs];
Scanner keyboard = new Scanner(System.in);
for (int div = 0; div < divs; div++) {
for (int qtr = 0; qtr < qtrs; qtr++) {
System.out.printf("Enter sales figures for division %d, quarter %d:", (div + 1), (qtr + 1));
errorCheck = keyboard.nextDouble();
while (errorCheck < 0) {
System.out.printf("Enter sales figures for division %d, quarter %d:", (div + 1), (qtr + 1));
errorCheck = keyboard.nextDouble();
}
sales[div][qtr] = errorCheck;
}
}
for (int qtr = 0; qtr < 4; qtr++) {
System.out.printf("Q%d:\n", (qtr + 1));
for (int div = 0; div < divs; div++) {
qtrsales[qtr] += sales[div][qtr];
System.out.printf("\tD%d: %.2f\n", (div + 1), sales[div][qtr]);
}
for (int qtrS = 0; qtrS < 1; qtrS++) {
System.out.printf("Total:" + qtrsales[qtr] + ", Change:");
System.out.printf("Average sales:" + (qtrsales[qtr] / divs));
}
for (int div = 0; div < 1; div++) {
highestDiv = 0;
if (sales[highestDiv][qtr] < sales[(div + 1)][qtr]) {
highestDiv = (div + 1);
}
highestDivi[qtr] = highestDiv;
System.out.println("Division with the highest sales:" + highestDivi[qtr]);
}
}
}
}
So here is the output that I think you want:
Q1:
D1: 1234.45
D2: 1232.54
D3: 23987.54
D4: 1233.56
D5: 234.56
D6: 1234.45
Total: 29157.10
Average sales: 4859.52
Division with the highest sales: 3
Q2:
D1: 234.56
D2: 1234.45
D3: 1232.54
D4: 23987.54
D5: 1233.56
D6: 234.56
Total: 28157.21 (change: 28157.21)
Average sales: 4692.87
Division with the highest sales: 4
Q3:
D1: 1233.56
D2: 234.56
D3: 1234.45
D4: 1232.54
D5: 23987.54
D6: 1233.56
Total: 29156.21 (change: 29156.21)
Average sales: 4859.37
Division with the highest sales: 5
Q4:
D1: 23987.54
D2: 1233.56
D3: 234.56
D4: 1234.45
D5: 1232.54
D6: 23987.54
Total: 51910.19 (change: 51910.19)
Average sales: 8651.70
Division with the highest sales: 1
IMPORTANT: If that's not what you want, then I've managed to fail at following directions and you probably shouldn't listen to anything else I have to say.
This output was had by making a number of small changes. Of course, I'm not going to hand them over to you (that would be doing your homework for you, and for that I would need to charge you an exorbitant sum of money) so instead I'll just point you in the right direction.
To start with, there is this bit of code:
for (int qtrS = 0; qtrS < 1; qtrS++)
Study that line of code carefully and discover what it is actually doing. I'll give you a hint: it isn't wrong necessarily, but there is something you could do to improve it.
You have a similar loop further down:
for (int div = 0; div < 1; div++)
Study this one more carefully - it may appear to have the same problem as the previous, but it does not. Once you solve this riddle, your remaining issues will present themselves more clearly. (Note: if your 'fix' causes your program to crash - good. Keep going, you're on the right track.)
In addition, I'd like to offer the following advice for that final loop:
Your data uses a zero-based index. Looking at your code, you already know this. Your output in some cases is one-based (you print Q1, not Q0). Again, looking at your code, you already know this. My advice is to be consistent about how you deal with this indexing discrepancy. Specifically, always index your data using zero-based indexes and only + 1 those indices when printing the output for the user.
Now... about that Change calculation. If you don't know how to do something, try explaining the problem to yourself in very clear and precise terms (like writing a program, but without the overhead of language syntax, array indexing and all that other complicated mumbo-jumbo.) If you did, it might sound something like this:
"I need to calculate the change for quarters 2-4. This means that I need to print a change for each of those quarters (Q2, Q3, Q4). More specifically, I'll need three "change values". How would a change value be calculated? Starting at one quarter and figuring out how much changed to the next? That's just a subtraction. So all I really need is find a way to get those two values (for each quarter) so I can perform that subtraction. Oh, and I have to make sure to only do it for those quarters (2-4)."
Remember, the trick is to bob your head while talking to yourself in the car so people think you're singing along.
Good luck.
I need help on how to minus out the value in my object which is (25) when a random number (num) has been generated. I have written my code below but there seem to be a problem in my last line.
StickBag s1 = new StickBag(25);
int randNum = 1 + (int)(Math.random()*2);
int num = 1 + (int)(Math.random()*11);
for(int i = 0; i < 25 ; i++)
{
if(randNum == 1)
{
System.out.println("Computer player 1 chooses " + num + " sticks. ");
StickBag = StickBag - num;
}
For e.g. If a random number that is generated is 5 , then the total value in my object (25) will minus the value that was generated randomly (5) and therefore my object will then have the value 20 in it
I hope i have made myself clear
The trouble with the line
StickBag = StickBag - num;
is that StickBag is the name of a class. You actually want to refer to an instance of that class.
In your program, you have an instance of StickBag called s1. Therefore, what you probably want to write is something like this:
s1.stickCount = s1.stickCount - num;
That's with the assumption that stickCount is a public attribute of the class StickBag, and that it's what gets initialized to the value 25 when you do new StickBag(25).
Let me suggest that you rename s1 to something more expressive, such as gameBag. That might not suit your particular concept, but whatever it is, try to use words rather than single letters and numbers.
Also, num is pretty vague and could be renamed to something more specific, such as playerMove. And you might want to use the -= operator to perform the subtraction. If you were to apply all three of my suggestions, the line would look like this:
gameBag.stickCount -= playerMove;
If stickCount is private and you have to access its value with getStickCount() and set its value with setStickCount(), you would write the following.
gameBag.setStickCount(gameBag.getStickCount() - playerMove);
Note that in this case you can't use the -= operator. (Some programming philosophies insist on using getters/setters and others don't. The debate isn't germane to this question and you can find plenty of material on it elsewhere.)