variables reverting to default value - java

I have my program nearly done where their are three classes: one driver class, one pizza class, and an order class that calculates the order price. My only issue is once I run my code the variables will set through the while loop in the inputToppings method of the pizza class and will print the correct values when the toString method is called from the pizza class in the order class but in my getToppingQuantity method it's passing the default values for the instance variables. Where am I going wrong here?
package edu.ilstu;
import java.util.Scanner;
public class Pizza
{
//default pizza is cheese and tomato sauce only
private int alfredo = 0;
private int pesto = 0;
private int tomato = 1;
private int sausage = 0;
private int pepperoni = 0;
private int onion = 0;
private int mushroom = 0;
private int greenPepper = 0;
private int cheese=1;
private char choice;
public int getCheese() {
return cheese;
}
public int getAlfredo()
{
return alfredo;
}
public void setAlfredo()
{
alfredo=1;
pesto=0;
tomato=0;
}
public int getPesto()
{
return pesto;
}
public void setSausage(int sausage)
{
this.sausage = sausage;
}
public void setPepperoni(int pepperoni)
{
this.pepperoni = pepperoni;
}
public void setOnion(int onion)
{
this.onion = onion;
}
public void setMushroom(int mushroom)
{
this.mushroom = mushroom;
}
public void setGreenPepper(int greenPepper)
{
this.greenPepper = greenPepper;
}
public void setCheese(int cheese)
{
this.cheese = cheese;
}
public void setPesto()
{
pesto=1;
tomato=0;
alfredo=0;
}
public int getTomato()
{
return tomato;
}
public void setTomato()
{
tomato=1;
pesto=0;
alfredo=0;
}
public int getSausage()
{
return sausage;
}
public int getPepperoni()
{
return pepperoni;
}
public int getOnion()
{
return onion;
}
public int getMushroom()
{
return mushroom;
}
public int getGreenPepper()
{
return greenPepper;
}
public void inputToppings() {
Scanner sc = new Scanner (System.in);
while (true) {
System.out.println("Input toppings. Enter Q to quit");
System.out.println("1. Sausage");
System.out.println("2. Pepperoni");
System.out.println("3. Onion");
System.out.println("4. Mushroom ");
System.out.println("5. Green Pepper");
System.out.println("6. Cheese");
System.out.println("7. Alfredo");
System.out.println("8. Pesto");
System.out.println("9. Tomato");
if (choice == 'q' || choice == 'Q') {
break;
}
if (choice == '1') {
addSausage();
}
if (choice == '2') {
addPepperoni();
}
if (choice == '3') {
addOnion();
}
if (choice == '4') {
addMushroom();
}
if (choice == '5') {
addGreenPepper();
}
if (choice == '6') {
addCheese();
}
if (choice == '7') {
if(alfredo != 1) {
setAlfredo();
}
else
System.out.println("No double sauce allowed");
}
if (choice == '8'){
if (pesto != 1) {
setPesto();
}
else
System.out.println("No double sauce allowed");
}
if (choice == '9') {
if(tomato != 1) {
setTomato();
}
else
System.out.println("No double sauce allowed");
}
choice = sc.next().charAt(0);
}//end while loop
sc.close();
}//end of inputToppings method
public void addCheese() {
if(cheese<2) {
setCheese(cheese+1);
}
else
System.out.println("Invalid input");
}
public void addPepperoni() {
if (pepperoni<2) {
setPepperoni(pepperoni+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public void addSausage() {
if(sausage<2) {
setSausage(sausage+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public void addOnion() {
if(onion<2) {
setOnion(onion+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public void addGreenPepper() {
if(greenPepper<2) {
setGreenPepper(greenPepper+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public void addMushroom() {
if(mushroom<2) {
setMushroom(mushroom+1);
}
else
System.out.println("Maximum ammount of topping exceeded");
}
public String toString() {
String str ="sausage = " + Integer.toString(sausage) + " Pepperoni = " + Integer.toString(pepperoni) + "\n" + "Onion = " + Integer.toString(onion) + " Mushroom = " + Integer.toString(mushroom) +"\n" + "cheese = " + Integer.toString(cheese) +"\n" + "Tomato = " + Integer.toString(tomato) + " Pesto = " + Integer.toString(pesto) + " Alfredo = " + Integer.toString(alfredo);
return str;
}
public int getToppingQuantity() {
return sausage+pepperoni+onion+mushroom+cheese;
}
}//end of class
here is the order class
public class Order
{
final double TAX_RATE = 0.075;
final double BASE_PRICE = 5.00;
final double TOPPING_CHARGE = 0.75;
final double DELIVERY_CHARGE = 0.10;
public char typeOfOrder;
public String storeLocation = "";
Pizza pizza1 = new Pizza();
Customer cust1 = new Customer();
public double calculateSubtotal() {
double toppingPrice = (pizza1.getToppingQuantity()*TOPPING_CHARGE);
return BASE_PRICE+toppingPrice;
}
public double calculateSalesTax() {
return calculateSubtotal()*TAX_RATE;
}
public double calculateDeliveryCharge() {
return (calculateSubtotal() + calculateSalesTax()) * DELIVERY_CHARGE;
}
public void displaySummary() {
if (typeOfOrder=='d' || typeOfOrder=='D') {
System.out.printf("Subtotal $%.2f\n", calculateSubtotal());
System.out.printf("Sales Tax: $%.2f\n", calculateSalesTax());
System.out.printf("Delivery Charge: $%.2f\n", calculateDeliveryCharge());
System.out.printf("Total: $%.2f\n", calculateSubtotal() + calculateSalesTax() + calculateDeliveryCharge());
System.out.println(pizza1.getToppingQuantity());
System.out.println("Thank you, come again!");
}
else if (typeOfOrder == 'p' || typeOfOrder == 'P') {
System.out.println(storeLocation);
System.out.printf("Subtotal $%.2f\n", calculateSubtotal());
System.out.printf("Sales Tax: $%.2f\n", calculateSalesTax());
System.out.printf("Total: $%.2f\n", calculateSubtotal() + calculateSalesTax());
System.out.println("Thank you, come again!");
}
}
public char getTypeOfOrder()
{
return typeOfOrder;
}
public void setTypeOfOrder(char typeOfOrder)
{
this.typeOfOrder = typeOfOrder;
}
public String getStoreLocation()
{
return storeLocation;
}
public void setStoreLocation(String storeLocation)
{
this.storeLocation = storeLocation;
}
}
and finally the driver class
public class PizzaDriver
{
public static void main(String[] args) {
Customer cust01= new Customer();
Order order01 = new Order();
Pizza pizza01 = new Pizza();
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to ILSTU Pizza");
System.out.println("Step 1: Is this for a pickup or delivery?");
System.out.println("1 Pickup");
System.out.println("2 Delivery");
int choice = sc.nextInt();
System.out.println("Choice: " + choice);
if (choice==1) {
order01.setTypeOfOrder('p');
System.out.println("1. 207 W. North St, Normal, IL");
System.out.println("2. 208 Landmark Dr, Bloomington, IL");
System.out.println("3. 1600 W. Market St, Bloomington, IL");
System.out.println("Which location would you like to pickup from?");
choice=sc.next().charAt(0);
if (choice=='1') {
order01.setStoreLocation("207 W. North St, Normal, IL");
}
else if (choice=='2') {
order01.setStoreLocation("208 Landmark Dr, Bloomington, IL");
}
else if (choice=='3') {
order01.setStoreLocation("1600 W. Market St, Bloomington, IL");
}
else
System.out.println("invalid choice");
System.out.println("At this stage would you like to quit this order entry process? \n Enter 'Y' to quit or 'N' to continue on to build your pizza.");
choice=sc.next().charAt(0);
if (choice=='N'|| choice == 'n') {
pizza01.inputToppings();
System.out.println("Your pizza contains the following toppings: \n" + pizza01.toString());
order01.displaySummary();
}
else if(choice == 'Y' || choice == 'y') {
System.out.println("Thank you, come again!");
}
}
else if (choice == '2') {
//System.out.println("Step 2: Customer Information");
order01.setTypeOfOrder('d');
sc.nextLine();
System.out.println("Please enter your first and last name: \n");
cust01.setFullName(sc.nextLine());
System.out.println("Please enter your street address");
cust01.setAddress(sc.nextLine());
System.out.println("Please enter your city, state and zip code");
cust01.setCityStateZip(sc.nextLine());
System.out.println("Please enter your phone number (10-dights only)");
String userNumber=sc.nextLine();
while(true) {
if (userNumber.length()==10) {
cust01.setPhoneNumber(userNumber);
break;
}
else if (userNumber.length()!=10) {
System.out.println("Invalid phone number, Enter a valid one");
}
userNumber=sc.nextLine();
}
System.out.println(cust01.toString()+"\n");
System.out.println("At this stage would you like to quit this order entry process? \n Enter 'Y' to quit or 'N' to continue on to build your pizza.");
choice=sc.next().charAt(0);
if (choice=='N'|| choice == 'n') {
pizza01.inputToppings();
System.out.println("\n Your pizza contains the following toppings: \n" + pizza01.toString());
order01.displaySummary();
}
else if(choice == 'Y' || choice == 'y') {
System.out.println("Thank you, come again!");
}
}
else
System.out.println("invalid choice");
}
}
like I said my program goes through the steps properly but returns the wrong value for the topping variables in the getToppingQuantity method (Note: I didn't include the customer class because it doesn't pertain to my current issue)

In your Order class you have a Pizza instance variable, but in your PizzaDriver you're creating and using a different Pizza object. This is likely the root cause of your issues. (You're also doing the same thing with the Customer class.)
This means that
System.out.println("\n Your pizza contains the following toppings: \n"
+ pizza01.toString());
...and...
order01.displaySummary();
Refer to different Pizza objects.

Your while(true) block in inputToppings() will never allow for an exit from the while condition (except in the break you provided to quit. Not that while(true) is an unacceptable programming practice, but it can lead to infinite loops. Better to provide a boolean flag, then exit once the value of the flag has changed.

Related

objects private member comparison with object passed as argument's private member not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 13 days ago.
This post was edited and submitted for review 13 days ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
We have to create an array of objects of inventory item.
We have to add items in the inventory, and store those items in array. In Buy or sell option, we have to update quantity of inventory items, using updateQuantity method.
The isEqual() method of FoodItem class, receives an object and then compares the itemcode of the object with the array of objects itemcode, and returns true/false accordingly.
The problem is, in isequal() method,the array object itemcode value shows me 0, and argument object's itemcode value is correct. I am not able to figure out, why array object's value not working inside is equalmethod
Code of FoodItem Class
'''java
import java.util.Scanner;
public class FoodItem {
private int itemCode,itemQuantityinStock;
private String itemName;
private float itemPrice,itemCost;
public FoodItem() {
this.itemCode = 0;
this.itemQuantityinStock = 0;
this.itemName = "NA";
this.itemPrice = 0.0f;
this.itemCost = 0.0f;
}
public boolean addItem(Scanner scanner)
{
while(true)
{
try {
System.out.println("Enter the code for the item:");
this.itemCode = scanner.nextInt();
break;
}
catch(InputMismatchException e){
scanner.next();
System.out.println("Invalid Code");
}
}
scanner.nextLine();
System.out.println("Enter the name for the item:");
itemName =scanner.nextLine();
System.out.println("Enter the quantity for the item:");
itemQuantityinStock =scanner.nextInt();
System.out.println("Enter the cost of the item:");
itemCost =scanner.nextFloat();
System.out.println("Enter the sales price of the item:");
itemPrice=scanner.nextFloat();
return true;
}
public boolean updateItem(int amount)
{
this.itemQuantityinStock +=amount;
return true;
}
**public boolean isEqual(FoodItem item)
{
System.out.println(itemCode + " comapre with "+item.itemCode );
if(itemCode == item.itemCode)
return true;
else
return false;
}**
public boolean inputCode(Scanner scanner)
{
while(true)
{
try {
System.out.println("Enter the code for the item:");
this.itemCode = scanner.nextInt();
break;
}
catch(InputMismatchException e){
scanner.next();
System.out.println("Invalid Code");
}
}
return true;
}
#Override
public String toString() {
return "\n\rItem: " + itemCode + " "+itemName + " " +itemQuantityinStock + " price: $"+itemPrice+ " cost: $" + itemCost;
}
}
'''
code of inventory class
import java.util.InputMismatchException;
import java.util.Scanner;
public class Inventory {
FoodItem inventory[]=new FoodItem[20];
FoodItem f2;
FoodItem fi;
int numItems;
public Inventory() {
this.numItems = 0;
}
public int alreadyExists(FoodItem item)
{
return 0;
}
public boolean addItem(Scanner scanner)
{
boolean success=true;
while(true)
{
scanner.nextLine();
System.out.println("Do you wish to add a fruit(f), vegetable(v), preserve(p)?");
char ch=scanner.nextLine().charAt(0);
if(ch=='F' || ch=='f')
{
inventory[numItems] = new Fruit();
inventory[numItems].addItem(scanner);
numItems++;
break;
}
else if(ch=='v' || ch=='V')
{
inventory[numItems] = new Vegetable();
inventory[numItems].addItem(scanner);
numItems++;
break;
}
else if(ch=='P' || ch=='p')
{
inventory[numItems] = new Preserve();
inventory[numItems].addItem(scanner);
numItems++;
break;
}
else
{
System.out.println("Invalid entry");
}
}
return success;
}
public void displayInventory()
{
for(int i=0;i<numItems;i++)
{
System.out.print(inventory[i].toString());
}
}
public boolean updateQuantity(Scanner scanner,boolean buyOrSell)
{
int qty;
if(numItems==0)
{
System.out.println("Error...could not buy item");
}
else
{
fi=new FoodItem();
if(fi.inputCode(scanner))
{
for(int i=0;i<numItems;i++)
{
f2=inventory[i];
System.out.println(f2.toString()); //working here
if(f2.isEqual(fi)) //not working here
{
if(buyOrSell == true)
{
while(true)
{
try {
System.out.println("Enter valid quantity to buy:");
qty=scanner.nextInt();
f2.updateItem(qty);
inventory[i] = f2;
}
catch(InputMismatchException e){
scanner.next();
System.out.println("Invalid Entry..");
}
}
}
else
{
while(true)
{
try {
System.out.println("Enter valid quantity to sell:");
qty=scanner.nextInt();
qty=-qty;
f2.updateItem(qty);
inventory[i] = f2;
}
catch(InputMismatchException iw)
{
scanner.next();
System.out.println("Invalid Entry..");
}
}
}
}//end of if
}//end of for
}//end of if
}//end of else
return true;
}
}

How to use control statements on a methods? if possible

I don't know how to say
if money(); < 1000 and house(); is == small print your poor
or
if money(); >=1000 and < 5000 and house(); is == to normal to print your ok, your too rich
package ArrayTest;
import java.util.Scanner;
/**
* Created by quwi on 02/12/2017.
*/`enter code here`
public class Happyness {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// house();
// money();
comparison();
}
private static void house() {
// getting user input and using the switch statement to see the size
// of their house
System.out.println("Please enter the size of your house ");
String cap = scanner.next();
switch (cap) {
case "small":
System.out.println("you have a small house it means your poor");
break;
case "normal":
System.out.println("your house normal, it mean your not poor nor rich");
break;
case "large":
System.out.println("your house is big it means your rich");
break;
default:
System.out.println("please choose between: small, normal or large");
break;
}
}
private static void money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
System.out.println("your poor");
} else if (wage >= 1000 && wage < 5000) {
System.out.println("your not poor, your OK");
} else if (wage > 5000) {
System.out.println("your rich, Give me money");
} else {
System.out.println("please enter a number nothing else");
}
}
private static void comparison() {
System.out.println("please enter a number");
int decision = scanner.nextInt();
switch (decision) {
case 1:
money();
break;
case 2:
house();
break;
case 3:
money();
house();
break;
default:
System.out.println("Please choose 1, 2 or 3");
}
}
}
Use return value from both to compare.
private static String money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
return "poor";
} else if (wage >= 1000 && wage < 5000) {
return "ok";
} else if (wage > 5000) {
return "rich";
} else {
//ask for input again or exit, whatever
}
}
Do same for the house(). Then, compare the return values from both in another method.

Java_Fill an array by getters

Trying to fill an array using getter, the problem the array is full with the same number and if the value change in the second input the hole array changes again :
public class Payment {
Scanner kb = new Scanner(System.in);
private int operationNum = 0;
private int subOperationNum = 0;
private double reMoney = 0;
public int getOperationNum() {
return operationNum;
}
public int getSubOperationNum() {
return subOperationNum;
}
public double getReMoney() {
return reMoney;
}
public void setOperationNum(int operationNum) {
this.operationNum = operationNum;
}
public void setSubOperationNum(int subOperationNum) {
this.subOperationNum = subOperationNum;
}
public void setReMoney(double reMoney) {
this.reMoney = reMoney;
}
public void operationsLoop() {
double [] a = new double[17];
do {
System.out.println("\n1- Cash");
System.out.println("2- Car");
System.out.println("3- Clothing");
System.out.println("4- Credit Card");
System.out.println("5- Food");
System.out.println("6- Education");
System.out.println("7- Electronics");
System.out.println("8- Groceries");
System.out.println("9- Health & Fitness");
System.out.println("10- Medical");
System.out.println("11- Travel");
System.out.println("12- Utilities");
System.out.println("13- Finish");
System.out.print("\nEnter the number of operation : ");
this.setOperationNum(kb.nextInt());
this.operation2();
this.operation12();
this.collectReMoney();
**for(int i = 0; i<a.length;i++){
a[i] = this.getReMoney();
System.out.print(a[i] + ", ");
}**
} while (operationNum < 13);
}
public void operation2() {
if (this.getOperationNum() == 2) {
System.out.println("\t1- Gas");
System.out.println("\t2- Repair");
System.out.println("\t3- Monthly Payment");
System.out.print("\nEnter your chose : ");
this.setSubOperationNum(kb.nextInt());
}
}
public void operation12() {
if (this.getOperationNum() == 12) {
System.out.println("\t1- Electricity");
System.out.println("\t2- Gas");
System.out.println("\t3- Telephone");
System.out.println("\t4- Water");
System.out.print("\nEnter your chose : ");
this.setSubOperationNum(kb.nextInt());
}
}
public void collectReMoney() {
if (this.getOperationNum() == 1) {
System.out.print("Withdraw = ");
this.setReMoney(kb.nextDouble());
} else if (this.getOperationNum() == 4 || (this.getOperationNum() == 2 && this.getSubOperationNum() == 3)) {
System.out.print("Payment = ");
this.setReMoney(kb.nextDouble());
} else if (this.getOperationNum() == 9 || this.getOperationNum() == 10) {
System.out.print("Pay = ");
this.setReMoney(kb.nextDouble());
} else if (this.getOperationNum() != 13) {
System.out.print("Spend = ");
this.setReMoney(kb.nextDouble());
}
}
and if I add to the array loop "this.setReMoney(0);" only the first value change
when the user enter a value i want to insert it in the array according to the operation number and the rest values of the other operations should be zero
In the for loop you are assigning the same number to each of the elements of the array, to avoid that you should take the assigning operation outside the for loop:
a[operationNum - 1] = this.getReMoney();
for(int i = 0; i<a.length;i++){
System.out.print(a[i] + ", ");
}
Also, make sure that you check for ArrayIndexOutOfBoundsException in the case the user selects an option number grater than the size of the array.

for each loop printing details from an arrayList using toString

I have been asked to :
 Create an EntertainmentRobot object and a HumanStudyRobot object (using the data previously
given) and store these objects in an array list.
 Set the purpose of each robot in the array using the data previously outlined in this paper.
 Print the details of each robot using the toString method.
I have did this and my code is below. But when I run the code, The details of each robot added to my arrayList are printed twice each. Any idea how I can fix it so that the details of each robot object in the array list only prints once? many thanks
package Program;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester04 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Robot> Robots = new ArrayList<Robot>();
HumanStudyRobot HumanStudyRobot1 = new HumanStudyRobot("HRP", 1.5, 58.0, "Kawada Industries");
HumanStudyRobot1.setPurpose("Study into human movement and perform a wide range of tasks.");
EntertainmentRobot EntertainmentRobot1 = new EntertainmentRobot("QRIO", 0.6, 7.3, "SONY");
EntertainmentRobot1.setPurpose("To live with you, make life fun and make you happy.");
Robots.add(EntertainmentRobot1);
Robots.add(HumanStudyRobot1);
for (Robot eachRobot : Robots) { //for loop to go through the array list
System.out.println(Robots.toString());
System.out.println("\n");
}
startRobot(Robots, input);
}
public static void startRobot(ArrayList<Robot> Robots, Scanner input){
for( int i = 0 ; i < Robots.size(); i++ ) {
Robots.get(i).start();
Robots.get(i).doTask();
Robots.get(i).doTask(input);
Robots.get(i).stop();
}
}
}
package Program;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class EntertainmentRobot extends Robot {
//constructor
public EntertainmentRobot(String name, double height, double weight, String manufacturer) {
super(name, height, weight, manufacturer);
this.energy = 10.0;
this.EnergyUnitsRequired = 0.75;
}
#Override
public void start() {
System.out.println("This is an Entertainment Robot. \nThe robot has started entertaining.");
}
#Override
public void stop() {
System.out.println("I have stopped entertaining people.");
System.out.println("--------------------------------------------------");
}
#Override
public void doTask(Scanner input) {
play();
talk();
walk();
}
#Override
public void doTask() {
// TODO Auto-generated method stub
}
public void talk() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a phrase for me to repeat");
String phrase = input.nextLine();
System.out.println("You have asked me to say the following phrase : " + phrase);
}
public void walk() {
Scanner input = new Scanner (System.in);
System.out.println("Would you like me to walk for you?");
if (input.nextLine().equalsIgnoreCase("Y")) {
System.out.println("For how many paces? ");
int steps = input.nextInt();
input.nextLine();
System.out.println("Which direction do you want me to walk? (Enter a number between 1 and 4.) ");
System.out.println("1 - " + Directions.FORWARD);
System.out.println("2 - " + Directions.BACKWARD);
System.out.println("3 - " + Directions.LEFT);
System.out.println("4 - " + Directions.RIGHT);
int selection = input.nextInt();
if (selection == 1 ) {
setDirection(Directions.FORWARD);
} else
if (selection == 2 ) {
setDirection(Directions.BACKWARD);
} else
if (selection == 3 ) {
setDirection(Directions.LEFT);
} else
if
(selection == 4 ) {
setDirection(Directions.RIGHT);
}
//output
System.out.println("I have walked " + getDirection() + " " + steps + " steps.");
}
else if (input.nextLine().equalsIgnoreCase("N")) {
System.out.println("Exitting the system.");
System.exit(0);
}
}
public void play () {
Scanner input = new Scanner(System.in);
boolean valid = false;
int selection;
do {
System.out.println("How many times would you like to play?");
while (!input.hasNextInt()) {
System.out.println("That is not a number");
input.nextLine();
}
selection = input.nextInt();
valid = true;
} while(!valid);
for (int i = 1; i < selection + 1; i ++ ) {
if (getEnergy() >= energyRequired()) {
energyConsumption();
} else if (getEnergy() < energyRequired()) {
System.out.println("------------WHOOPS--------------.");
System.out.println("I do not have enough energy to play.");
regenerate();
}
}
//input.close();
}
public String toString() {
return "---------------------------------\nI AM AN ENTERTAINMENT ROBOT \nThe details of the entertainment robot are below: \n" +
"Name : " + getName() + "\nWeight: " + getWeight() + "\nHeight: " + getHeight() + "\nManufacturer: " +
getManufacturer() + "\nPurpose: " + getPurpose() + "\n----------------------------";
}
}
package Program;
import java.util.Scanner;
public class HumanStudyRobot extends Robot {
//instance variables
public HumanStudyRobot(String name, double height, double weight, String manufacturer) {
super(name, height, weight, manufacturer);
this.energy = 30.0;
}
#Override
public void start() {
System.out.println("This is a Human Study Robot");
System.out.println("The robot has started studying.");
}
#Override
public void stop() {
System.out.println("The robot has finished studying.");
}
#Override
public void doTask() {
study();
walk();
}
#Override
public void doTask(Scanner input) {
// TODO Auto-generated method stub
}
public void study() {
if (energy >= energyRequired()) {
energyConsumption();
}
else
if (energy < energyRequired()) {
System.out.println("The robot does not have sufficient energy.");
regenerate();
System.out.println("................");
System.out.println("The robot has finished regenerating");
}
}
public String toString() {
return "I AM A HUMAN STUDY ROBOT : \nThe details of the human study robot are below:\n"
+ "Name : " + getName() + "\nWeight: " + getWeight() + "\nHeight: "
+ getHeight() + "\nManufacturer : " + getManufacturer() + "\nPurpose : "
+ getPurpose();
}
public void walk() {
int steps;
boolean valid = false;
Scanner input = new Scanner(System.in);
System.out.println("Would you like me to walk for you?");
if (input.nextLine().equalsIgnoreCase("Y")){
do {
System.out.println("I can only walk 10 paces at a time");
System.out.println("For how many paces? ( Enter a no. between 1 and 10 )");
while (!input.hasNextInt()) {
System.out.println("That is not a number");
input.nextLine();
}
steps = input.nextInt();
valid = true;
} while(steps < 0 || steps > 10);
System.out.println("Which direction do you want me to walk? ( Enter a number between 1 and 4, the options are below.");
System.out.println("1 - " + Directions.FORWARD);
System.out.println("2 - " + Directions.BACKWARD);
System.out.println("3 - " + Directions.LEFT);
System.out.println("4 - " + Directions.RIGHT);
int selection = input.nextInt();
if (selection == 1 ) {
setDirection(Directions.FORWARD);
} else if (selection == 2 ) {
setDirection(Directions.BACKWARD);
} else if (selection == 3 ) {
setDirection(Directions.LEFT);
} else if (selection == 4 ) {
setDirection(Directions.RIGHT);
}
else System.out.println("That is not a valid selection.");
System.out.println("I have walked " + getDirection() + " " + steps + " steps");
}
}
}
You did'nt write the foreach loop in a right way ...
for (Robot eachRobot : Robots) { //for loop to go through the array list
System.out.println(Robots.toString());
System.out.println("\n");
}
And this will print the whole list elements as :
ArrayList<Integer>lists=new ArrayList<Integer>();
lists.add(new Integer(50));
lists.add(new Integer(70));
for (Integer integer : lists) {
System.out.println(lists.toString());
}
will print :
[50, 70]
[50, 70]
So change the loop to print each element toString function It should written like :
for (Robot eachRobot : Robots) { //for loop to go through the array list
System.out.println(eachRobot .toString()+"\n");
// println is already print new line for you if you want to print two lines you can use that instead.
}
Rewrite the loop and test ..

Why am I getting the error "the Method Is Undefined for the type"?

I am learning the basics at University and would like some help with the following error from Eclipse : "The method getCost() is undefined for the type ShopCLI" &
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getCost() is undefined for the type ShopCLI
at components.ShopCLI.main(ShopCLI.java:39)
Here is my code
public class ShopCLI {
public static void main(String[] args) {
ArrayList<Order> ord = new ArrayList<>();
System.out.println("Welcome to Sandwich Shop CLI V1!");
System.out.println("Please Choose and Option by Typing the Appropriate Number from the List");
System.out.println("1.New Order");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
System.out.println("Please Choose an Outer From the List: ");
System.out.println("Press 1 to Continue or 2 to Exit");
int Sandwich = sc.nextInt();
System.out.println("Outer Options are Bun, Bread or Brioche");
String inputOuter = sc.next();
System.out.println("Inner Options are Ham, Cheese or Cucumber");
String inputInner = sc.next();
System.out.println("Sauce Options are Mayo, Butter or Marmite");
String inputSauce = sc.next();
if (Sandwich == 1){
ord.add(new Order(1, inputOuter, inputInner, inputSauce, 0));
System.out.println("You Made a " + inputInner + " with " + inputSauce + " Sandwich on " + inputOuter);
System.out.println("This Will Cost " + getCost());
}
else if (Sandwich == 2){
System.out.println("Exited.");
}
}
}
public class Sandwich {
//Fields
ArrayList<Sandwich> sandwich = new ArrayList<>();
String outer;
String inner;
String sauce;
//Constructor
public Sandwich(String outer, String inner, String sauce){
this.outer = outer;
this.inner = inner;
this.sauce = sauce;
}
//Methods
public String getOuter(){
return outer;
}
public String getInner(){
return inner;
}
public String getSauce(){
return sauce;
}
public void setOuter(String repOuter){
outer = repOuter;
}
public void setInner(String repInner){
inner = repInner;
}
public void setSauce(String repSauce){
sauce = repSauce;
}
public void createSandwich(String outer, String inner, String sauce){
sandwich.add(new Sandwich(outer, inner, sauce));
}
public void setSandwich(String repOuter, String repInner, String repSauce){
outer = repOuter;
inner = repInner;
sauce = repSauce;
}
public void resetOrder(){
sandwich.removeAll(sandwich);
}
}
public class Order extends Sandwich {
//Fields
int OrderId;
double Cost;
//Constructor
public Order(int OrderId, String outer, String inner, String sauce, int Cost) {
super(outer, inner, sauce);
this.OrderId = OrderId;
this.Cost = Cost;
}
//Methods
public int getOrderId(){
return this.OrderId;
}
public double getCost(){
return this.Cost;
}
public void setOrderId(int repOrderID){
this.OrderId = repOrderID;
}
public void overrideCost(int Cost){
this.Cost = Cost;
}
public void setOrder(int repOrderId, String repOuter, String repInner, String repSauce){
this.OrderId = repOrderId;
this.outer = repOuter;
this.inner = repInner;
this.sauce = repSauce;
double calcCost;
double outerCost = 0;
double innerCost = 0;
double sauceCost = 0;
//Outer Cost
if(repOuter == "Bun")
{
outerCost = 0.5;
}
else if(repOuter == "Bread")
{
outerCost = 0.25;
}
else if(repOuter == "Brioche")
{
outerCost = 0.75;
}
else
{
System.out.println("Invalid Bread Type");
}
//Inner cost
if(repInner == "Ham")
{
innerCost = 0.5;
}
else if(repInner == "Cheese")
{
innerCost = 0.25;
}
else if(repInner == "Cucumber")
{
innerCost = 0.75;
}
else
{
System.out.println("Invalid Filling Type");
}
//Sauce Cost
if(repSauce == "Mayo")
{
sauceCost = 0.5;
}
else if(repSauce == "Butter")
{
sauceCost = 0.25;
}
else if(repSauce == "Marmite")
{
sauceCost = 0.75;
}
else
{
System.out.println("Invalid Sauce Type");
}
calcCost = outerCost + innerCost + sauceCost;
this.Cost = calcCost;
}
}
getCost method is defined in order class and not in ShopCLI class. So your code:
ord.add(new Order(1, inputOuter, inputInner, inputSauce, 0));
System.out.println("You Made a " + inputInner + " with " + inputSauce + " Sandwich on " + inputOuter);
System.out.println("This Will Cost " + getCost());
Should be changed to
Order order = new Order(1, inputOuter, inputInner, inputSauce, 0);
ord.add(order);
System.out.println("You Made a " + inputInner + " with " + inputSauce + " Sandwich on " + inputOuter);
System.out.println("This Will Cost " + order.getCost());
^^^^^
you must get the object from the arraylist, then do acces the method:
//get obj,then void
System.out.println("This Will Cost " + ord.get(choise).getCost());
this will return 0, since you set the cost 0 in the constructor:
ord.add(new Order(1, inputOuter, inputInner, inputSauce, 0));
also, name your integer "Sandwich" to "sandwich" without the capital letter. otherwise, it looks like you mean the class "Sandwich"
In this line:
System.out.println("This Will Cost " + getCost());
...you don't specify what you want to call getCost() on, so it calls it on ShopCLI because that's where the call is happening. But ShopCLI doesn't have a getCost() method. You need to call it on your order:
System.out.println("This Will Cost " + ord.get(0).getCost());
This works, but when you create your Order object by calling the constructor, you're not calculating the cost, but rather setting whatever is passed in. Update your constructor to this:
//Constructor
public Order(int OrderId, String outer, String inner, String sauce) {
super(outer, inner, sauce);
this.OrderId = OrderId;
double calcCost;
double outerCost = 0;
double innerCost = 0;
double sauceCost = 0;
//Outer Cost
if(outer == "Bun")
{
outerCost = 0.5;
}
else if(outer == "Bread")
{
outerCost = 0.25;
}
else if(outer == "Brioche")
{
outerCost = 0.75;
}
else
{
System.out.println("Invalid Bread Type");
}
//Inner cost
if(inner == "Ham")
{
innerCost = 0.5;
}
else if(inner == "Cheese")
{
innerCost = 0.25;
}
else if(inner == "Cucumber")
{
innerCost = 0.75;
}
else
{
System.out.println("Invalid Filling Type");
}
//Sauce Cost
if(sauce == "Mayo")
{
sauceCost = 0.5;
}
else if(sauce == "Butter")
{
sauceCost = 0.25;
}
else if(sauce == "Marmite")
{
sauceCost = 0.75;
}
else
{
System.out.println("Invalid Sauce Type");
}
calcCost = outerCost + innerCost + sauceCost;
this.Cost = calcCost;
}
Now your constructor works, but you will have to remove an argument where you're calling it, so change your ord.add line to this:
ord.add(new Order(1, inputOuter, inputInner, inputSauce));
That should, if I'm not mistaken work. However, you might want to consider making a private helper method called calculateCost, so that you're not duplicating code between your constructor and your setOrder methods.
Create an Order
Order order = new Order(1, inputOuter, inputInner, inputSauce, 0);
ord.add(order) // Add the order to your list.
The cost for an order is set by the method setOrder(int repOrderId, String repOuter, String repInner, String repSauce)
change this method to the following.
public void setOrder() {
double calcCost;
double outerCost = 0;
double innerCost = 0;
double sauceCost = 0;
// Outer Cost
if (outer.equalsIgnoreCase("Bun")) {
outerCost = 0.5;
} else if (outer.equalsIgnoreCase("Bread")) {
outerCost = 0.25;
} else if (outer.equalsIgnoreCase("Brioche")) {
outerCost = 0.75;
} else {
System.out.println("Invalid Bread Type");
}
// Inner cost
if (inner.equalsIgnoreCase("Ham")) {
innerCost = 0.5;
} else if (inner.equalsIgnoreCase("Cheese")) {
innerCost = 0.25;
} else if (inner.equalsIgnoreCase("Cucumber")) {
innerCost = 0.75;
} else {
System.out.println("Invalid Filling Type");
}
// Sauce Cost
if (sauce.equalsIgnoreCase("Mayo")) {
sauceCost = 0.5;
} else if (sauce.equalsIgnoreCase("Butter")) {
sauceCost = 0.25;
} else if (sauce.equalsIgnoreCase("Marmite")) {
sauceCost = 0.75;
} else {
System.out.println("Invalid Sauce Type");
}
calcCost = outerCost + innerCost + sauceCost;
this.Cost = calcCost;
}
Now you can get the cost by calling the getCost() on the order as follows.
To calculate the order cost, call
order.setOrder();
To get the order cost, call
order.getCost();
NOTE: Don't use == to compare string. Always use equals() or equalsIgnoreCase().
i have modified your code for class ShopCLI
package tester;
import java.util.ArrayList;
import java.util.Scanner;
public class ShopCLI {
public static void main(String[] args) {
ArrayList<Order> ord = new ArrayList<>();
int orderNumber =1;
System.out.println("Welcome to Sandwich Shop CLI V1!");
System.out.println("start order");
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("Press 1 for new order or 2 to Exit");
int choice = sc.nextInt();
if (choice == 1){
System.out.println("Enter outer Options:Outer Options are Bun, Bread or Brioche");
String inputOuter = sc.next();
System.out.println("Enter inner Options:Inner Options are Ham, Cheese or Cucumber");
String inputInner = sc.next();
System.out.println("Enter sauce Options:Sauce Options are Mayo, Butter or Marmite");
String inputSauce = sc.next();
Order order1 = new Order(orderNumber, inputOuter, inputInner, inputSauce, 0);
order1.setOrder(inputOuter, inputInner, inputSauce);
System.out.println("You Made a " + inputInner + " with " + inputSauce + " Sandwich on " + inputOuter);
System.out.println("This Will Cost " + order1.getCost());
ord.add(order1);
}
else if (choice == 2){
System.out.println("Exited.");
System.exit(1);
}
}
}
}
and format of setOrder method is modified too
public void setOrder(String repOuter, String repInner, String repSauce)

Categories

Resources