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.
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 just started learning how to program in Java. Everything was going well so far.. That was until I came across this "bonus" question/problem our teacher gave us to solve as an additional "challenge".
Please click here to view the Question and the Sample input/output (it's an image file)
Note that I'm not allowed to use anything that wasn't taught or discussed in class. So, things like arrays, method overloading, parsing arrays to methods, parseInt, etc. gets ruled out.
Here's what I was able to come up with, so far:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
int N; // number of lines of input
double length1, length2, length3; // the 3 lengths
double perimeter; // you get this by adding the 3 lengths
double minperimeter=0; // dummy value
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of triangles you have:");
N = input.nextInt();
System.out.println("Insert the lengths of the sides of these " +
"triangles (3 real numbers per line):");
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
minperimeter = Math.min(perimeter,Math.min(perimeter,perimeter));
}
System.out.printf("The minimum perimeter is %.1f%n", minperimeter);
}
}
My 2 main problems are:
1) The program only stores and works with the 'last' input.
The ones before it get replaced with this one. [update: solved this problem]
2) How do I print the "triangle number" in the final output? [update: solved this problem, too]
So, can anyone please help me come up with a solution that requires only the very basic learnings of Java? If it helps, this is the book we're using. Currently at Chapter 4. But we did learn about Math Class (which is in Chapter 5).
Update: Thank you so much for your replies, everyone! I was able to come up with a solution that does exactly what was asked in my question.
Math.min(perimeter,perimeter) will always give you perimeter. You probably wanted to do Math.min(perimeter,minPerimeter)
Since it's a programming assignment is best if I don't give you the full solution to your second question, but your hint is, in the counter parameter of your for loop. Save that when you update minperimeter, so that you know in which iteration of the loop you found the minimum.
Also, initialise your minPerimeter to 10000 or higher. If you start at 0, Math.Min will never be lower than that.
Change your for loop as:
double minperimeter=-1;
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter = (length1 + length2 + length3);
if(minperimeter == -1){
minperimeter = perimeter;
} else{
Math.min(perimeter,minperimeter);
}
}
You have to store the smaller perimeter in your variable perimeter.
The hint from your task tells you, that any given perimeter is smaller than 1000. Thus initiate the perimeter to 1000.
In your for-loop then you have to store the smaller perimeter:
perimeter = Math.min(perimeter, length1 + length2 + length3)
if the sum of the edges is smaller than the current perimeter, the smaller value will be stored.
Please note that according to your given task, you have to input 3 doubles within one line.
Alternative Solution
Make an ArrayList and add all perimeter to that list and then find the minimum value from that list.
List<Double> perimeter = new ArrayList<>();
for (int counter=0; counter<N; counter++)
{
length1 = input.nextDouble();
length2 = input.nextDouble();
length3 = input.nextDouble();
perimeter.add(length1 + length2 + length3);
}
System.out.printf("The minimum perimeter is %.1f%n", Collections.min(perimeter));
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.)
DISCLAIMER : I DO NOT WANT THE ANSWER TO THIS PROBLEM. I SIMPLY NEED SOME GUIDANCE.
I want to perform Monte Carlo analysis on the infamous Birthday Paradox (determining the probability that at least 2 people in a given group share the same birthday) using a HashSet.
Now when I run this, the collisionCount is WAY lower than I expected it to be.First, I was expecting the collisionCount for a group of 10 people to be 11446 (or a probability of 0.11446). Then by the time I got to 100 people, I was expecting the collisionCount to be 100,000 (with a probability of 1.0). But instead, for every 10 people, the collisionCount only counts by 1 (10 people: 1 collision, 20 people: 2 collisions, 30 people: 3 collisions, etc).
Here is the code I have wrote so far :
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class BirthdayParadox
{
public static void main(String [] args)
{
Random rand = new Random();
int tests = 100000;
int collisionCount = 0;
for(int people = 10; people <= 100; people += 10)
{
Set<Integer> birthdays = new HashSet<>(365);
birthdays.add(rand.nextInt(365));
for(int runs = 0; runs < tests; runs++)
{
int randomBirthday = rand.nextInt(365);
if(birthdays.contains(randomBirthday))
{
collisionCount++;
break;
}
birthdays.add(randomBirthday);
}
float prob = (float)collisionCount / tests;
System.out.println("After " + tests + " tests there were " +
collisionCount + " occurrences of shared " +
" birthdays in a set of " + people + " people.");
System.out.println("Probability : " + prob);
}
}
}
I guess my question is : Am I not doing something right with either of my for-loops in order to get the collisionCount to count correctly?
I am new to learning Java and I am new to the Stack Overflow community and am still learning the ropes. Any help/ advice/ tips are greatly appreciated.
Your problem appears to be that you are missing one of your loops.
Notice that your runs loop is broken by the first collision. This means that your value will never be more than 1.
Also, you never use your people variable inside the inner loop except when outputting results.
What you need to do is run your simulation 100_000 times. The way to do this is to place logic within your runs loop that checks if people people will have a birthday collision and then iterate your collision count.
I think that the java solution is not the best, this probably it is the problem why you have a difference between the simulation and the mathematical values. What i understand for the problem is that you have to determine for a group of 10 people (in this case) how many of them share the same birthday. To do that you have to random an array of 10 with number from 0 to 365 (days of the year) and count how many of them are the same. You have to do that severals time (100000 in your case).
I think that you have to invert the FOR order. I mean..
for(int runs = 0; runs < tests; runs++)
{
//initialize an array of 10
for(int people = 0; people <= 10; people +=1)
{
//random birthdayDay
//array [people] = rand.nextInt(365);
}
//check if there is a collision
//If there is one you have to increase you success variable in 1
}
//calculate the probability
I try to help you, doing kind of pseudocode.
Hope that this help you a little bit.
Regards
Arturo.