Here are the instructions I have for a class project that I've given up on.
The constructor should call the appropriate set methods of the String class, to assign the values passed as parameters to the instance variables size and toppings
I have a constructor of a Pizza class but it will not keep the parameter values for size and toppings that I pass to it even if I use size = this.size. I don't understand what set method my teacher is referring to. All I need is the conceptual understanding and I will be able to do complete this project.
edit: to be clear, I know my code gives a NPE right now, because my variable toppings is null in toString(), so I'm trying to pass the toppings that has been changed by Pizza() to toString()
public class Pizza {
private char size;
private String[] toppings;
private int status;
public final static int NOT_STARTED = 0;
public final static int IN_PROGRESS = 1;
public final static int READY = 2;
public static void main(String[] args) {
String[] testArray = new String[]{"poop", "pee"};
Pizza newpizza2 = new Pizza('L', testArray);
System.out.println(newpizza2.toString());
}
//Boolean method with a char parameter that checks the size and sets the char of the pizza size (S,M,L) and returns true.
public boolean setSize(char size2) {
if (size2 == 'S'||size2 == 'M'||size2 == 'L') {
size = size2;
return true;
}
else {
size = 'M';
return false;
}
}
//Boolean method with an int parameter that checks the status and sets the status of the pizza readiness.
public boolean setStatus(int status2) {
if (status2 >= NOT_STARTED && status2 <= READY) {
status = status2;
return true;
}
else {
status = NOT_STARTED;
return false;
}
}
//Void method with a String array parameter that only sets the toppings from user input and returns no value.
public void setToppings(String[] toppings) {
toppings = this.toppings;
}
//A Get method for setSize to return the value of size.
public char getSize() {
return this.size;
}
//A Get method for setStatus to return the value of status.
public int getStatus() {
return this.status;
}
//A Get method for setToppings to return the value of toppings[].
public String[] getToppings() {
return this.toppings;
}
//Int method that checks the number of toppings and returns the amount of toppings or 0 if there are no toppings given.
public int numToppings() {
if (toppings != null) {
return toppings.length;
}
else {
return 0;
}
}
//Method that calculates the price of the pizza based on the instance variables and returns the price.
public double calcPrice() {
if (size == 'S') {
double price = 8;
double toppingPrice = toppings.length;
double total = price + toppingPrice;
return total;
}
else if (size =='M') {
double price = 9;
double toppingPrice = 0;
if (toppings != null) {
toppingPrice = toppings.length * 1.5;
}
double total = price + toppingPrice;
return total;
}
else if (size =='L') {
double price = 10;
double toppingPrice = toppings.length * 2;
double total = price + toppingPrice;
return total;
}
else {
return 0;
}
}
/********************************/
//No argument Constructor//
public Pizza() {
size = 'M';
status = NOT_STARTED;
toppings = null;
}
public Pizza(char size, String[] toppings) {
size = this.size;
System.out.println(toppings.length);
status = NOT_STARTED;
}
public String statusPhrase() {
if (status == NOT_STARTED) {
return "Not Started";
}
else if (status == IN_PROGRESS) {
return "In Progress";
}
else {
return "Ready";
}
}
public String toString() {
String combo, combo2 = "", combo3;
Pizza newpizza = new Pizza();
newpizza.setSize(size);
newpizza.setToppings(toppings);
//Print out the method's return values
if (toppings.length == 0) {
combo = "Pizza size " + newpizza.getSize() + ". No toppings.";
}
else {
combo = "Pizza size " + newpizza.getSize() + ". Toppings: ";
}
//List the toppings in number order using a for loop
for (int i = 0; i<=newpizza.numToppings()-1; i++){
combo2 += "\n" + (i+1)+ ". " + newpizza.getToppings()[i];
}
combo3 = "\n"+newpizza.statusPhrase();
return combo + combo2 + combo3;
}
}
It's really simple:
private char someChar;
public void setSomeChar (char someChar) {
this.someChar = someCHar; // 'this' refers to THIS instance.
}
It is also important to know that the thing on the left site is the one the value gets passed to (excuse my english).
When you write:
private char someChar;
public void setSomeChar (char someChar) {
someChar = this.someCHar; //
}
you pass the value of the instance variable to the local method parameter (they coincidentally have the same name).
To say it a little more generally:
private char instanceVariable;
public void someMethod (char someLocalParameter) {
/* local means that it is only known inside this method. That's why everything
* you assign to it just disappears after executing the method.
*/
someLocalParameter = this.instanceVariable // nothing happens
this.instanceVariable = someLocalParameter // will do the job
}
This your current constructor
public Pizza(char size, String[] toppings) {
size = this.size;
System.out.println(toppings.length);
status = NOT_STARTED;
}
Your constructor should look like this
public Pizza(char size, String[] toppings) {
this.size = size;
this.toppings = toppings
System.out.println(toppings.length);
status = NOT_STARTED;
}
Related
I am new to Java programming. I developed a Pizza class that takes for parameters and outputs the description and cost. I developed a PizzaOrderArray class that stores the pizza orders in an array. I have a class containing the main method also.
When I tried to print the values of the orders, nothing prints yet debugging shows that the proper methods and loops were entered.
What am I doing incorrect? I have invested many hours and am still very confused. Any suggestions, please? Thank you! I appreciate it.
Pizza.java
import java.text.NumberFormat;
import java.util.Locale;
public class Pizza {
public Pizza(String size, int numCheeseTop, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
setNumCheese(numCheeseTop);
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_pep = 0;
setNumHam(numHamTop);
pizza_cheese = 0;
}
public Pizza(String size) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza() {
pizza_size = "small";
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza(Pizza copyPizza) {
pizza_size = copyPizza.getPizzaSize();
pizza_cheese = copyPizza.getNumCheese();
pizza_pep = copyPizza.getNumPep();
pizza_ham = copyPizza.getNumHam();
}
//Setters
public boolean setPizzaSize(String size) {
if (size.equalsIgnoreCase("small") || (size.equalsIgnoreCase("medium") || (size.equalsIgnoreCase("large")))) {
pizza_size = size.toLowerCase();
return true;
}
return false;
}
public void setNumCheese(int numCheeseTop) {
pizza_cheese = numCheeseTop;
}
public void setNumPep(int numPepTop) {
pizza_pep = numPepTop;
}
public void setNumHam(int numHamTop) {
pizza_ham = numHamTop;
}
//End of setters
//Getters
public String getPizzaSize() {
return pizza_size;
}
public int getNumCheese() {
return pizza_cheese;
}
public int getNumPep() {
return pizza_pep;
}
public int getNumHam() {
return pizza_ham;
}
//End of getters
public double calcCost() {
if (pizza_size.toLowerCase() == "small") {
return 10 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "medium") {
return 12 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "large") {
return 14 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() != "small" && pizza_size.toLowerCase() != "medium"
&& pizza_size.toLowerCase() != "large") {
System.out.println("Invalid pizza size");
return 0;
}
return 0;
}
public String getDescription() {
return pizza_size + " pizza with " + pizza_cheese + " cheese toppings " + pizza_pep + " pepperoni toppings and "
+ pizza_ham + " ham toppings "; //+ " which is " + money.format(pizza2.calcCost());
}
//private String pizza_size;
//private int pizza_cheese, pizza_pep, pizza_ham;
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
} //End of Pizza class
PizzaOrderArray.java
import static java.lang.System.out;
public class PizzaOrderArray {
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
//private String pizza_size;
//private int pizza_cheese; pizza_pep; pizza_ham;
private Pizza[] pizza;
private int index = 0;
public PizzaOrderArray() {
System.out.println("PizzaOrderArray()");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(int i) {
System.out.println("PizzaOrderArray(int i)");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(PizzaOrderArray poa) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa)");
pizza = new Pizza[poa.index];
index = poa.index;
for (int i = 0; i < poa.index; i++) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa) for loop");
pizza[i] = new Pizza(poa.pizza[i]);
}
}
public void setPizza(int index1, Pizza newpizza) {
System.out.println("Inside of setPizza");
pizza[index1] = new Pizza(newpizza);
}
public String getPizzaSize() {
System.out.println("Inside of getPizzaSize");
return pizza_size;
}
public int getNumCheese() {
System.out.println("Inside of getNumCheese");
return pizza_cheese;
}
public int getNumPep() {
System.out.println("Inside of getNumPep");
return pizza_pep;
}
public int getNumHam() {
System.out.println("Inside of getNumHam");
return pizza_ham;
}
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for (int i = 0; i < indexUsed; i++) {
s = (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
return s;
}
public double calcTotal() {
double r = 0.0;
System.out.println("Inside of calcTotal");
for (int i = 0; i < index; i++) {
System.out.println("Inside of calcTotal for loop");
r = r + pizza[i].calcCost();
}
return r;
}
public boolean equals(PizzaOrderArray orderarray) {
boolean r = false;
System.out.println("Inside of equals");
if (orderarray.pizza.length != pizza.length) {
System.out.println("Inside of equals if");
return r;
}
for (int i = 0; i < orderarray.pizza.length; i++) {
if (pizza[i].equals(orderarray.pizza[i])) {
System.out.println("Inside of equals for-if");
r = true;
} else {
System.out.println("Inside of equals for-else");
return false;
}
}
System.out.println("Return of equals");
return r;
}
} //End of PizzaOrderArray class
V4_Project_15_page_418.java
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.Arrays;
public class V4_Project_15_page_418 {
public static void main(String args[]) {
//Order1
PizzaOrderArray order1 = new PizzaOrderArray();
Pizza pizzaone = new Pizza("Medium", 0, 0, 0);
Pizza pizzatwo = new Pizza("Small", 1, 0, 0);
order1.setPizza(0, pizzaone);
System.out.println("Order 1: ");
System.out.println(order1.toString());
System.out.println(order1);
System.out.println();
//Order2
Pizza pizzathree = new Pizza(pizzatwo);
PizzaOrderArray order2 = new PizzaOrderArray(2);
order2.setPizza(0, pizzaone);
order2.setPizza(0, pizzatwo);
System.out.println("Order 2: ");
System.out.println(order2.toString());
System.out.println(order2);
System.out.println();
//Order3
PizzaOrderArray order3 = new PizzaOrderArray(1);
order3.setPizza(0, pizzaone);
order3.setPizza(0, pizzatwo);
System.out.println("Order 3: ");
System.out.println(order3.toString());
System.out.println(order3);
System.out.println();
//Order4
PizzaOrderArray order4 = new PizzaOrderArray(order3);
System.out.println("Order 4: ");
System.out.println(order4.toString());
System.out.println(order4);
//TEST THE PROGRAM
System.out.println("TEST: The total for order 4 is: " + order4.calcTotal());
System.out.println();
//Order5
PizzaOrderArray order5 = new PizzaOrderArray(order1);
System.out.println("Order5: ");
System.out.println(order5);
System.out.println();
}//End of main class
}//End of V4_Project_15_page_418 class
Output:
PizzaOrderArray()
Inside of setPizza
Order 1:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 2:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 3:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order 4:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
Inside of calcTotal
Inside of calcTotal for loop
Invalid pizza size
TEST: The total for order 4 is: 0.0
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order5:
Inside of toString
Inside of toString for loop
Take a close look at the condition in this for loop, it isn't going to ever print anything since the condition is never true since i is never less than indexUsed which is 0.
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
return s;
}
Something also need pay attention to:
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
means:
for(int i = 0; i < indexUsed; i++) {
s= (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
So this is System.out.println just misleading you, you are never "inside of" the for loop.
I think it's better to always use the braces '{}' with for/while loop.
The snippet
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString()); is wrong, your for loop is never executed since indexUsed is 0
In your toString method, the for loop condition never becomes true (before the first iteration itself, 0<0 becomes false & loop terminates without executing once) so the loop never executes.
You can try changing the for loop statement to:
for(int i = 0; i < index; i++)
I have written a program which takes the words the user have entered, with a button press, and puts them in an ArrayList. There is also another text field where the user can enter a letter or word, for which the user can search for in the ArrayList with another button press. I'm using a sequential search algorithm to accomplish this, but it does not work as I expect it to; If the searched word is found, the search function should return, and print out in a textArea that the word was found and where in the array it was found. This works, but only for the first search. If the word is not found, the function should print out that the word was not found. This works as I want it to.
The problem is that after I searched for one word, and it displays where in the ArrayList this can be found, nothing happens when I press the button after that, whether the entered letter/word is in the array or not. It's like the string that the text gets stored isn't changing. I don't understand why... Here below is the custom Class of the search function and then my Main class:
public class Search {
static private int i;
static String index;
static boolean found = false;
public static String sequencial (ArrayList<String> list, String user) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
index = "The word " + user + " exist on the place " + i + " in the Arraylist";
found = true;
}
}
if (!found) {
index = "The word " + user + " could not be found";
}
return index;
}
My Main class:
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> s = new ArrayList<String>();
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtaOutput.setText("");
String word = txtfAdd.getText();
list.add(word);
for (int i = 0; i < list.size(); i++) {
txtaOutput.append("" + list.get(i) + "\n");
}
}
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String user = txtfSearch.getText();
txtaOutput.setText("");
String index = Search.sequencial(list, user);
txtaOutput.setText("" + index);
}
Any help is appreciated!
The problem is that you declared your found variable as static. When your first word is found, it is set to true, and nothing ever sets it back to false. Instead of making it a static variable, declare it as a local variable inside your sequencial (it's spelled sequential, by the way) function, just before the for-loop.
In fact, all the variables you've declared as static should be made local. Declaring static variables is never a good idea.
As said by other users:
There is the List#indexOf(Object) method. You should use that instead of reinventing the wheel (unless you need to, and in that case you might have a look at the ArrayList implementation). There are also other collections, like HashSet which are more apropiate for looking up, but i guess that is another history.
The scope and the names of the variables (i, index, found) is error-prone. Do other methods or even classes need to have access to those variables? If you need to keep those variables, you might want to choose a visibility (public,protected,private). "index" is a misleading choice of a name for a message.
This would be an slightly simplified/corrected version of your code:
// Ommit those unneeded static variables
public static String sequencial (ArrayList<String> list, String user) {
int indexFound = list.indexOf(user);
if (user >= 0) {
return "The word " + user + " exist on the place " + indexFound + " in the Arraylist";
} else {
return "The word " + user + " could not be found";
}
}
...
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
String user = txtfSearch.getText();
// txtaOutput.setText("");
String seqMessage = sequencial(list, user);
txtaOutput.setText(seqMessage);
}
We use the static properties when you would like to use the constants. You should not use the static properties here. The problem will happen when your found property is changed the first time, it will not be changed again. And from that time, it will always be true. Similar with index property. Here is the code you can fix this:
public class Search {
public static SearchResult sequencial (ArrayList<String> list, String user) {
SearchResult result = null;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
String index = "The word " + user + " exist on the place " + i + " in the Arraylist";
boolean found = true;
result = new SearchResult(index, found);
break;
}
}
if (result == null) {
String index = "The word " + user + " could not be found";
result = new SearchResult(index);
}
return result;
}
//sample inner class
static class SearchResult {
private String index;
private boolean found;
public SearchResult(String index) {
this.index = index;
}
public SearchResult(String index, boolean found) {
this.index = index;
this.found = found;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public boolean isFound() {
return found;
}
public void setFound(boolean found) {
this.found = found;
}
}
}
public class SequencialSearcher {
public static int SequencialSearchInt(int[] inputArray, int key)
{
for(int i=0; i < inputArray.length ; i++)
{
if(inputArray[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchString(String[] array, String key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchFloat(double[] array, double key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static void main (String args[])
{
//select the type of the elements of search
//1 if integers
//2 if float
//3 if string
int x = 3;
int[] array1 = {9, 0, 10, 8, 5, 4, 6, 2, 3};
double[] array2 = {9.0, 0.0, 10.0, 8.0, 5.0, 4.0, 6.0, 2.0, 3.0};
String[] array3 = {"aa","hey", "hello"};
if(x == 1){
//enter the integer you want to search for here below
int requiredValue = 5;
int result = SequencialSearchInt(array1, requiredValue);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue+" not found");
}
}
else if(x == 2)
{
//enter the double you want to search for here below
double requiredValue1 = 5.0;
int result = SequencialSearchFloat(array2, requiredValue1);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue1+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue1+" not found");
}
}
else if(x == 3){
//enter the string you want to search for here below
String requiredValue2 = "hey";
int result = SequencialSearchString(array3, requiredValue2);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue2+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue2+" not found");
}
}
else{
System.out.println("Error. Please select 1,2 and 3 only");
}
}
}
Can someone see why the user can enter more than 27 apple, blueberry, or peanut pies? Even after declaring a final int for the max number of each type of pie.
The object here is to continually prompt the user for type of pie until the user wants to quit. Each time one of the valid inputs is entered it is stored in it's own array. After the user has indicated they are finished, calculations are done and a message is printed.
import javax.swing.JOptionPane;
public class CalcPieProfit {
public static void main(String[] args) {
final int MAX_PER_TYPE = 27;
int appleTotal = 0;
int blueberryTotal = 0;
int peanutTotal = 0;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
else if (typeOfPie.equalsIgnoreCase("blueberry")) {
String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
blueberryTotal++;
}
else if (typeOfPie.equalsIgnoreCase("peanut")) {
String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
peanutTotal++;
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleTotal, blueberryTotal, peanutTotal);
double profit = calcProfit(appleTotal, blueberryTotal, peanutTotal);
printReport(totalPies, appleTotal, blueberryTotal, peanutTotal, profit);
}
}
public static String getPieType() {
String pieType;
do {
try {
pieType = JOptionPane.showInputDialog("Enter a pie type:");
}
catch (NumberFormatException e) {
pieType = "";
}
if (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q")) {
JOptionPane.showMessageDialog(null, "Enter 'apple', 'blueberry', 'peanut', or 'q' only.");
}
} while (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q"));
return pieType;
}
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
public static String[] fillBlueberry(String typeOfPie, int MAX_PER_TYPE) {
String[] blueberryArray = new String[MAX_PER_TYPE];
for (int i = 0; i < blueberryArray.length; i++) {
blueberryArray[i] = typeOfPie;
}
return blueberryArray;
}
public static String[] fillPeanut(String typeOfPie, int MAX_PER_TYPE) {
String[] peanutArray = new String[MAX_PER_TYPE];
for (int i = 0; i < peanutArray.length; i++) {
peanutArray[i] = typeOfPie;
}
return peanutArray;
}
public static int calcTotalPies(int appleTotal, int blueberryTotal, int peanutTotal) {
int total = appleTotal + blueberryTotal + peanutTotal;
return total;
}
public static double calcProfit (int appleTotal, int blueberryTotal, int peanutTotal) {
final double APPLE_PROFIT = 5.94;
final double BLUEBERRY_PROFIT = 5.89;
final double PEANUT_PROFIT = 6.95;
double profit = (APPLE_PROFIT * appleTotal) + (BLUEBERRY_PROFIT * blueberryTotal) +
(PEANUT_PROFIT * peanutTotal);
return profit;
}
public static void printReport(int totalPies, int appleTotal, int blueberryTotal, int peanutTotal, double profit) {
if (totalPies > 0) {
JOptionPane.showMessageDialog(null,
"Pie Report\n\n" +
"Total pies: " + totalPies +
"\nTotal of apple pie: " + appleTotal +
"\nTotal of blueberry pie: " + blueberryTotal +
"\nTotal of peanut butter pie: " + peanutTotal +
"\nTotal profit: $" + String.format("%.2f", profit));
}
else {
JOptionPane.showMessageDialog(null, "Enjoy your day off.");
}
}
}
You are not really using the String[]s appleArray, blueberryArray and peanutArray - they are created in their respective method but not used anywhere else. For calculating the profits, you are (rightfully) only the total variables.
Instead of
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
you should do something like
if (typeOfPie.equalsIgnoreCase("apple")) {
if (appleTotal >= MAX_PER_TYPE) {
JOptionPane.showMessageDialog(null, "Too many apples.");
} else {
appleTotal++;
}
}
(and the same for other pie types).
You're redeclaring the pie arrays each time you go to add them.
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
Each time you call this method, a new "appleArray" is generated. If you want it to persist between calls to this method, declare the appleArray as private static outside of the loop, and reference that instead.
In the method askCarType() and askSolarPanel() the inputdialog both run two times, once in their own method and once more in the final method PrintOptions().
I need them to only run once, and that is in the final method PrintOptions().
How can I do that?
import javax.swing.*;
public class short7 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintOptions();
}// ends main
public static String askCarType() {
String typeOfCar;
typeOfCar = JOptionPane.showInputDialog("Electric or Hybrid?");
if (!typeOfCar.equals("Electric")
&& (!typeOfCar.equals("electric") && (!typeOfCar
.equals("Hybrid") && (!typeOfCar.equals("hybrid"))))) {
JOptionPane
.showMessageDialog(null,
"You have to choose either an Electric or Hybrid type of car.");
typeOfCar = JOptionPane.showInputDialog("Electric or Hybrid?");
}
return typeOfCar;
}// ends askCarType
public static String askSolarPanel() {
String wantSolarPanel;
wantSolarPanel = JOptionPane
.showInputDialog("Do you want a Solar Panel?");
if (!wantSolarPanel.equals("Yes")
&& (!wantSolarPanel.equals("yes") && (!wantSolarPanel
.equals("No") && (!wantSolarPanel.equals("no"))))) {
JOptionPane.showMessageDialog(null,
"You have to enter either Yes or No");
wantSolarPanel = JOptionPane
.showInputDialog("Do you want a Solar Panel?");
}
return wantSolarPanel;
}// ends askSolarPanel
public static int calculateDiscount() {
String typeOfCarSelected = askCarType();
String SolarPanelSelected = askSolarPanel();
int Discount = 0;
if ((typeOfCarSelected.equals("Electric") || typeOfCarSelected
.equals("electric"))
&& ((SolarPanelSelected.equals("Yes") || SolarPanelSelected
.equals("yes")))) {
Discount = 500;
} else {
Discount = 0;
}
return Discount;
}// ends calculateDiscount
public static int CalculateCost() {
String typeOfCarCost = askCarType();
String SolarPanelCost = askSolarPanel();
final int basicPrice = 20000;
final int ElectricModel = 2000;
final int SolarPanel = 5000;
final int Discount = calculateDiscount();
int total = 0;
if ((typeOfCarCost.equals("Electric") || typeOfCarCost
.equals("electric"))
&& ((SolarPanelCost.equals("No") || SolarPanelCost.equals("no")))) {
total = basicPrice + ElectricModel;
System.out.println("Basic Price:" + basicPrice);
System.out.println("Electric Model:" + ElectricModel);
System.out.println("Total:" + total);
} else if ((typeOfCarCost.equals("Electric") || typeOfCarCost
.equals("electric"))
&& ((SolarPanelCost.equals("Yes") || SolarPanelCost
.equals("yes")))) {
total = basicPrice + ElectricModel + SolarPanel - Discount;
System.out.println("Basic Price:" + basicPrice);
System.out.println("Electric Model:" + ElectricModel);
System.out.println("Solar Panel:" + SolarPanel);
System.out.println("Discount:" + Discount);
System.out.println("Total:" + total);
} else {
total += basicPrice;
System.out.println("Basic Price:" + basicPrice);
System.out.println("Total:" + total);
}
return total;
}// ends CalculateCost
public static void PrintOptions() {
CalculateCost();
}// ends PrintOptions
}// ends class short7
you're calling askCarType() and askSolarPanel() twice and what you need is call them one time !, so call them in CalculateCost() and sent the two string typeOfCarCost and SolarPanelCost to the calculateDiscount method like this :
public static int calculateDiscount(String typeOfCarSelected, String SolarPanelSelected) {
int Discount = 0;
if ((typeOfCarSelected.equals("Electric") || typeOfCarSelected.equals("electric")) && ((SolarPanelSelected.equals("Yes") || SolarPanelSelected.equals("yes")))) {
Discount = 500;
} else {
Discount = 0;
}
return Discount;
}//ends calculateDiscount
and in CalculateCost()
public static int CalculateCost() {
String typeOfCarCost = askCarType();
String SolarPanelCost = askSolarPanel();
final int basicPrice = 20000;
final int ElectricModel = 2000;
final int SolarPanel = 5000;
final int Discount = calculateDiscount(typeOfCarCost, SolarPanelCost);/////here you send the input fromthe user to this method without needing to call it again
int total = 0;
....
}
You can declare two class variables.
String typeOfCar;
String wantSolarPanel;
And in askCarType() method assign
typeOfCar = ................
and in askSolarPanel() method assign
wantSolarPanel = .....................
Then use these variables from CalculateCost() and calculateDiscount() rather than calling askCarType() and askSolarPanel() method again.
I'm trying to add elements to an array. The elements of the array are of a custom class called variable. In the problematic for loop, it basically adds the last element trying to be added throughout the loop. Any help would be appreciated!
import java.util.*;
public class ThiefsDilemma2{
public static void main(String[] args){
ArrayList values = new ArrayList(args.length/2);
Valuable[] array = new Valuable[args.length/2];
if(args.length%2 ==1){
int weight = Integer.parseInt(args[args.length-1]);
boolean room = true;
int tracker = 0;
//problem!!!! Adds the last element throughout the loop
for(int i = 0; i < args.length/2; i++){
array[i] = new Valuable(
Integer.parseInt(args[args.length/2+i]),
Integer.parseInt(args[i]));
}
for(int i = 0; i < args.length/2; i++){
System.out.println(array[i]);
}
while(values.size() > 0 && room){
int lightest = 100000;
double value = 0.0;
int index = 0;
int counter = 0;
for(Object p: values){
Valuable test = (Valuable)p;
//System.out.println(test);
if(test.getWeight() < lightest && !test.beenUsed()){
lightest = test.getWeight();
//System.out.println(lightest);
}
if(test.getValue() > value && !test.beenUsed()){
index = counter;
value = test.getValue();
//System.out.println(value);
}
else if(test.getValue() == value || !test.beenUsed()){
if(test.getWeight() <= test.getWeight()){
index = counter;
}
}
counter++;
}
//System.out.println(counter + " " + lightest + " " + value);
Valuable p = ((Valuable)(values.get(index)));
p.used();
if(lightest > weight){ room = false;}
else{
if(p.getWeight() <= weight){
weight -= p.getWeight();
}
System.out.println(p);
values.remove(p);
}
}
}
}
public static class Valuable{
private static double value;
private static int weight;
private static boolean used = false;
public Valuable(int top, int bottum){
value = ((double)top/(double)bottum);
weight = bottum;
//System.out.println(weight + " " + value);
}
public static double getValue(){
return value;
}
public static int getWeight(){
return weight;
}
public String toString(){
return value + " " + weight;
}
public static void used(){
used = true;
}
public static boolean beenUsed(){
return used;
}
}
}
The problem is that all data members of Valuable are static. This means that they are shared by all instances of the class:
private static double value;
private static int weight;
private static boolean used = false;
Remove the static qualifiers from the data members, and from the getter functions.