I have an assignment for my coding class, I've done most of it, but i don't know how to do the last part.
This is the assignment "Create a class Plant for a Plant Nursery that has five attributes related to plants:
Maximum Height in feet
Common name
Scientific name
Price
Whether or not it is fragile.
Create two methods of your own choosing for the class Plant.
Allow the user to create a Plant object from the console. After the plant object is created, add the object to an ArrayList of Plants.
Allow the user to edit any information about the plant objects already entered.
...And for 10 Extra Credit points!! Allow the user to view the plants sorted by price (lowest to highest), scientific name (alphabetized by genus), or common name (alphabetized by first letter of first word).
Assignment is individual."
my code
class nursery{
private int height;
private String cName;
private String sName;
private int cost;
private boolean fragile;
public nursery(int height, String cName, String sName, int cost, boolean fragile)
{
this.height=height;
this.cName=cName;
this.sName=sName;
this.cost=cost;
this.fragile=fragile;
}
}
public class Nursery {
public static void main(String[] args) {
ArrayList<nursery> plant = new ArrayList<>();
Scanner s = new Scanner(System.in);
while(true){
//get the plant varibles
System.out.println("Enter the common name of the plant: ");
String cName = s.next();
System.out.println("Enter the scientific name of the plant: ");
String sName = s.next();
System.out.println("Enter the height of the plant: ");
int height = s.nextInt();
System.out.println("Enter whether the plant is fragile or not: ");
boolean fragile =s.nextBoolean();
System.out.println("Enter the price of the plant: ");
int cost=s.nextInt();
//add to the arraylist
nursery Plant = new nursery(height, cName, sName, cost, fragile);
plant.add(Plant);
System.out.println("If u would like to stop entering press q.");
String quit = s.next();
//quit out if wanted
if(quit.equals("q")||quit.equals("Q"))
break;
}
}
}
what I don't know how to do is "Allow the user to edit any information about the plant objects already entered." I've tried searching but I've been unable to get an answer.
You have preserved all the nursery objects (planet) to ArrayList<nursery> plant, so what you need to do is just find it from the list and reset its values.
A general example could be like:
nursery plant_to_update = null;
for (int i=0; i<plant.length; i++){
current_plant = plant.get(i);
// say user want to update planet with cName as 'planet 1'
if(plan_to_update.cName == "planet 1"){
plant_to_update = current_plant;
break;
}
}
if( plant_to_update != null){
// update planet 1 with new value
plant_to_update.setHeight(50);
plant_to_update.setCost(60);
}
and, add setters in nursery class in order to update those private members
public void setHeight(int height){
this.height = height;
}
public void setCost(int cost){
this.cost = cost;
}
Related
My template opens with a menu of options. When the user chooses option 1, it asks them to input a number teamNumber. One must instantiate the class Team, then it writes it to an arraylist.
If there is at least one number in numberList, the user can select option 2. It asks them to input any of the numbers from the arraylist and searches it. If the number they input is found, then you input the team member. It will write the input to a private arraylist located in class TeamMember.
I'm very close to figuring this all out except for one problem. It seems that regardless of which stored team number I input after choosing option 2, the team member I add to teamList is added to ALL team numbers, not just the one I want it to be added to. So, say in option 1 I added a team 1 and a team 2. Then in option 2, I type 1 and proceed to enter the member. It ends up adding the team member to both team 1 and 2. Is there a way to fix this? I tried a few options but can't seem to wrap my head around it.
public class Main {
public static void main(String[] args) {
int choosing;
Scanner scan = new Scanner(System.in);
String input;
int teamNumber;
boolean stayInLoop;
ArrayList<Team> numberList = new ArrayList<Team>();
do {
stayInLoop = true;
System.out.println("1. Add a new team");
System.out.println("2. Add a new team member");
System.out.println("3. View teams");
input = scan.nextLine();
if (input.equals("1")) {
System.out.println("Enter a team number:");
teamNumber = scan.nextInt();
scan.nextLine();
Team addTeam = new Team(teamNumber);
numberList.add(addTeam);
}
if (input.equals("2")){
boolean foundIt = false;
boolean valid = true;
System.out.println("Team number:");
teamNumber = scan.nextInt();
scan.nextLine();
for (int a = 0; a < numberList.size() && foundIt == false; a++){
Team addTeam = numberList.get(a);
if (addTeam.findTeam() == teamNumber) {
foundIt = true;
System.out.println("Enter first name of team member:");
String teamMemberFirstName = scan.nextLine();
System.out.println("Enter first initial of last name:");
char firstInitialLastName = scan.nextLine().charAt(0);
TeamMember inputTeamMember = new TeamMember(teamMemberFirstName, firstInitialLastName);
inputTeamMember.addMember(inputTeamMember, valid = true);
int teamSize = (inputTeamMember.size(valid = true));
System.out.println("Team " + teamNumber + " has " + teamSize + " members!");
}
}
if (foundIt == false) {
System.out.println("Try again.");
}
}
}while (stayInLoop == true;)
}}
TeamMember:
public class TeamMember {
//the code provided in the task had teamList set to private, so I'm assuming it's required to be that way. I added static in order to eventually be able to call it with a method to view the team in option 3. But if the only solution involves changing the list to public, then so be it.
private final String teamMemberFirstName;
private final char firstInitialLastName;
private static ArrayList<TeamMember> teamList = new ArrayList<>();
public TeamMember(String teamMemberFirstName, char firstInitialLastName) {
this.teamMemberFirstName = teamMemberFirstName;
this.firstInitialLastName = firstInitialLastName;
}
public int addMember(TeamMember member, boolean valid) {
valid = teamList.add(member);
return teamList.size();
}
public static int size(boolean valid) {
return teamList.size();
}
}
teamList is static, hence shared by all instances of TeamMember. Remove the static keyword.
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 7 years ago.
Improve this question
I have this main class
public class Hotel
{
Scanner scan = new Scanner(System.in);
Register[] items = new Register[15];
int count = 0;
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register deluxe = new Deluxe();
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
run.enterItems();
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
}
public double calcTotal()
{
double total = 0;
for(int i = 0;i<count;i++)
{
total += items[i].total();
}
return total;
}
that is supposed to return the value i put in in the scanner here in the enterItems() that is in the class as the main class
public void enterItems()
{
int type, quantity, sale,night;
double price;
............................
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
}
So this will pass to the class called Deluxe where i have this method called displayInfo()
public class Deluxe implements Register
{
int quantity,night;
double sale;
public Deluxe(){}
....................................
public double total()
{
double total, price = 200.0;
price = price*quantity*night;
total = price - (price * (sale/100));
total += total *.06;
return total;
}
public void displayInfo(){
if (quantity > 0){
System.out.println("Room Type : Deluxe Room");
System.out.println("Quantity: " +quantity);
System.out.println("Discount: " +sale);
}
}
}
the problem is, in checking for quantity > 0, it actually does not get any value that i put in in the scanner. It will always return 0 for quantity regardless what amount i put in.
But the calculation works fine. Calculation is to calculate how many (quantity) rooms book x night stay x the room's price.
The calculation is also in the same class as the displayInfo() which is in class Deluxe.
So i was wondering what did i do wrong here.
The quantity which you input here:
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
Goes into main(String[] args).quantity that's defined here:
public class Hotel
{
....
public static void main(String[] args)
{
...
int quantity, sale,night;
...
}
The quantity that you check here:
if (quantity > 0){...}
Is a different parameter - it's Deluxe.quantity and is defined here:
public class Deluxe implements Register
{
int quantity,night;
...
}
Those two parameters have no relation. If you want them both to be the same, you need to pass to class Deluxe the main(String[] args).quantity parameter. You can do this via your own constructor under Hotel.main(String[] args), like so:
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
quantity = run.enterItems();
Register deluxe = new Deluxe(quantity,0,0); // entering the default value for the other two parameters like the empty constructor would leave them.
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
if you change your enterItems() function to return the quantity parameter you need, like so:
public int enterItems()
{
int type, quantity, sale,night;
double price;
.........
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
return quantity;
}
Notice, this solves this only for the quantity parameter. if you need more, you might need to return the Deluxe structure from enterItems(). Good luck!
newbie here at Java. I'm working on a project to where I collect info from a user for two types of Creatures. The menu would look like:
1. Land based
2. Water based
3. Display Animal
4. Quit.
I'm wanting to collect the user information from the user and then display it back to them. I think I'm stuck on building the object constructors from the different object.
Here's what I have so far:
SuperClass:
package com.animal;
public class Creature {
private String size;
private String weight;
public Creature (String size, String weight){
this.size = size;
this.weight = weight;
}
public String getSize() {return size;}
public void setSize(String size) {this.size = size;}
public String getWeight() {return weight; }
public void setWeight(String weight) {this.weight = weight; }
void displayCr(){
System.out.println("***Creatures***");
System.out.println("Size: " + size);
System.out.println("Weight: " + weight);
This is my Land Subclass:
package com.animal;
public class Land extends Creature {
private String landAnimal;
public String getLandAnimal() {return landAnimal;}
public void setLandAnimal(String landAnimal) {this.landAnimal = landAnimal;}
public Land(String size, String weight, String landAnimal) {
super(size, weight);
this.landAnimal = landAnimal;
This is my Water subclass:
package com.animal;
public class Water extends Creature {
private String fish;
public String getFish() {return fish;}
public void setFish(String fish) {this.fish = fish;}
public Water(String size, String weight, String fish) {
super(size, weight);
this.fish = fish;
}
Then this is my Main called Kingdom:
package com.animal;
import java.util.ArrayList;
import java.util.Scanner;
public class Kingdom {
public static void main(String[] args) {
ArrayList<Creature> user = new ArrayList<Creature>();
Scanner input = new Scanner(System.in);
int selection = 0;
while(selection != 4){
System.out.println("****Main Menu****");
System.out.println("Enter 1 for Land Animal");
System.out.println("Enter 2 for Water Animal");
System.out.println("Enter 3 to Display Animal");
System.out.println("Enter 4 to quit");
selection = input.nextInt();
if(selection==1 || selection==2){
Creature userInfo = null;
System.out.println("Enter Size ");
String size = input.next();
System.out.println("Enter Weight: ");
String weight = input.next();
}
if(selection == 1){
System.out.println("Enter Land animal type: ");
String landAnimal = input.next();
//userInfo = new Land(size, weight, landAnimal);
//user.add(userInfo);
}
else if(selection == 2){
System.out.println("Enter Water animal type: ");
String fish = input.next();
//userInfo = new Water(size, weight, fish);
}
//creature.add(userInfo);
//System.out.println(user.displayCr());
}
I feel like I'm on the right path, but the last steps just aren't clicking for me and I've been grinding on this, reading, videos and nothing is clicking.
Also, I apologize if I've made the newbie mistakes in this post. I will accept all criticism, suggestions and help as a positive lesson. Thanks.
Overall your code is fairly right.
Except:
Creature userInfo = null; you are defining it inside the first IF, its scope will be limited to that IF.
As soon as you leave that IF it ceases to exist, hence you can't use it in the following IFs.
Consider the following scope change:
if(selection==1 || selection==2){ // main IF
Creature userInfo = null;
...
if(selection == 1){
...
}
else {
...
}
System.out.println(userInfo.displayCr());
} // end of main IF
First of all expand the scope of size,weight and userInfo means keep it inside main but outside the conditions as it is being used everywhere. Something like this.
int selection = 0;
String size = null;
String weight = null;
Creature userInfo = null;
Instead of this
creature.add(userInfo); should be
user.add(userInfo);
and call display like this
userInfo.displayCr(); because the return type of the method is void so cannot be used inside sysout and it should be inside that else if(){}
I'm working on an assignment for a low-level java class. I have it mostly finished, but I'm stuck on how to use an ArrayList. There are two classes, the second one (PizzaMaker) is the client. I need to initialize an ArrayList in the first class and then add three items to it via user input from the client. I know how to initialize the ArrayList, but I'm having problems adding items to the list. When I run the code I have now, it returns with empty brackets [ ] or null.
I'm not expecting someone to do my homework for me, but a clue as to where I'm going wrong with this code would be helpful.
import java.util.*;
public class Pizza {
private String brand;
private int size;
private ArrayList<String> toppings = new ArrayList<String>();
public Pizza(String brand, int size) {
this.brand = brand;
this.size = size;
}
public void changeBrand(String brandName) {
brand = brandName;
}
public void changeSize(int pizzaSize) {
size = pizzaSize;
}
public void addTopping(String topping) {
toppings.add("topping");
}
public String getPizzaInfo() {
String result = "You want a "+ size +" inch pizza made by: "+ brand +" with these
toppings:" + toppings;
return result;
}
}
public class PizzaMaker {
public static void main( String[] args) {
int size = -1;
String brand = "";
String topping = "";
brand = getBrand();
size = getSize();
topping = getTopping();
Pizza newPizza = new Pizza(brand, size);
System.out.println(newPizza.getPizzaInfo());
}
public static String getBrand() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a brand name: ");
String brandName = kb.nextLine();
return brandName;
}
public static int getSize() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a size: ");
int pizzaSize = kb.nextInt();
kb.nextLine();
return pizzaSize;
}
public static String getTopping() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter topping: ");
String topping = kb.nextLine();
return topping;
}
public static boolean getAgain() {
return true;
}
}
You need to call addTopping. Eg, newPizza.addTopping(topping). Also, correct the addTopping method. Replace toppings.add("topping") with toppings.add(topping);
And I am sure you need to put more effort to learn Java :)
You never added any toppings to your pizza,
Pizza newPizza = new Pizza(brand, size);
// Keep adding toppings, check for empty string to end?
while ((topping = getTopping()).length() > 0) {
newPizza.addTopping(topping); // <-- add the topping to the pizza.
}
System.out.println(newPizza.getPizzaInfo());
You also need to fix your method addTopping
public void addTopping(String topping) {
// toppings.add("topping");
toppings.add(topping);
}
As you specifically asked not to have us do your homework for you (which is good :) ) I will only give you the clues and pseudocode for what you need to do:
Right now you are just creating the Pizza object in PizzaMaker, but you are not doing anything with it. You have already created the methods to retrieve the toppings in PizzaMaker, the method getTopping(). You also have the method to add the toppings to the pizza in Pizza which is addTopping(). Now you just need to call the methods from PizzaMaker so they will be used.
The psuedocode should be like this:
Create the pizza object
For the number of toppings you want to add call getTopping()
For each topping you get you need to add that topping to you Pizza object with your addTopping() method.
Once all the toppings have been added, you can print out your pizza object.
It looks like you want to be able to ask the user for multiple toppings. So as a first approximation, let's assume the topics are single word only, separated by commas (something easy to test using the Scanner you have set up). I recommend two changes to your source code:
First, change the ArrayList of toppings to be called toppingList
private ArrayList<String> toppingList = new ArrayList<String>();
Next, change the addToppings(String toppings) to break the tuple entered by the user into tokens (delimited by spaces):
public void addToppings(String toppings) {
// Let's assume the user enters all toppings as single words delimited
// / by space
StringTokenizer strtok = new StringTokenizer(toppings);
while (strtok.hasMoreTokens()) {
String topping = strtok.nextToken();
toppingList.add(topping);
}
}
Lastly, you will need to call the addToppings method from your main program:
public static void main(String[] args) {
int size = -1;
String brand = "";
String topping = "";
brand = getBrand();
size = getSize();
topping = getTopping();
Pizza newPizza = new Pizza(brand, size);
newPizza.addToppings(topping);
System.out.println(newPizza.getPizzaInfo());
}
One final note: make sure to close your Scanner instances, or you will have a resource leak. It's okay for this simple program, but if it were long-running, you have memory leaks.
To beef up your program, you could try:
Use a different delimiter, allowing multiple words in your toppings (like "Canadian Bacon" - two words),
Modify the getTopping() method to ask for the toppings one-at-a-time until the user presses some special key ("q to quit" is always a good one).
Have fun!
First mistake is you are not calling the methods you have defined in Pizza Class.
You are simply passing by constructor and initilizing the class variable and displaying those variable, but you are not passing the tropping value by constructor.
These below methods you are not calling anywhere .
/*public void changeBrand(String brandName) {
brand = brandName;
}
public void changeSize(int pizzaSize) {
size = pizzaSize;
}*/
Just Use this below code:-
public static void main( String[] args) {
int size = -1;
String brand = "";
String topping = "";
brand = getBrand();
size = getSize();
topping = getTopping();
Pizza newPizza = new Pizza(brand, size);
newPizza.addTopping(topping);
System.out.println(newPizza.getPizzaInfo());
}
Output :-
Enter a brand name:
Manoj
Enter a size:
20
Enter topping:
pizaset 1
You want a 20 inch pizza made by: Manoj with these toppings:[pizaset 1]
Hope it will help you.
Its working now, I have tested.
I've already created the ticketAgent and ticketType class and I'm having a tough time trying to add the strings. I've tried using a wrapper class but not sure if that's even the right approach. I've pasted my code and then the prompt respectively. Thanks for the help. I'm a first time poster, so I hope I've followed the posting guidelines.
Prompt:
Write a program called TicketBooth that instantiates at 3 different ticket agents. The TicketBooth program should prompt the user for the ticket agent they wish to purchase a ticket from and then display the list of ticket types and prices that are available. The TicketBooth program should allow the user to make a selection for the ticket to purchase. After a ticket type is selected, the TicketBooth program should display the:
• total sales for that ticket agent
• total number of tickets sold by the ticket agent
• total number of tickets sold by all ticket agents
The TicketBooth program should continue to prompt the user to purchase tickets from one of the ticket agents until the user types quit.
package Exercises;
import java.util.Scanner;
public class TicketBooth {
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
String ticketAgent = "sam", "nicole" , "alex";
String ticketType = "one";
int t = Integer.parseInt(ticketAgent);
int s = Integer.parseInt(ticketType);
int sum;
System.out.println("Please select your ticket agent: ");
ticketAgent = input.next();
System.out.println("Please select your ticket type or press -1 to quit: ");
ticketType = input.next();
sum = t +s;
System.out.println("The total tickets that were sold were: " + sum);
}
}
package exercises;
public class TicketAgent {
private static int numOfTicksPerAgent;
private String agentName;
private int numSold = 0;
private double totalSales = 0.0;
public TicketAgent(String agent) {
agentName = agent;
numSold = 0;
totalSales = 0.0;
numOfTicksPerAgent += 1;
}
public void sellTicket(TicketType tt) {
numSold++;
totalSales = totalSales + tt.getticketPrice();
numOfTicksPerAgent++;
}
public double gettotalSales() {
return totalSales;
}
public double getnumSold() {
return numSold;
}
public double getnumOfTicksPerAgent() {
return numOfTicksPerAgent;
}
}
package exercises;
public enum TicketType
{
CHILD (6.50),
ADULT (9.50),
SENIOR (6.50);
private double tikPrice;
TicketType(double price)
{
tikPrice = price;
}
public double getticketPrice()
{
return tikPrice;
}
}
The problem is, that it seems that this is your homework and
nobody wants to make your homeworks for you.
edit: I saw that you added your classes just now.
All you have to do is to add the do while loop
and instantiate your Agents in the right way.
Where, exactly, is your problem? So we can help you better.
My first approach would be, to make it simple,
to write a TicketAgent class and a TicketType class.
Write the TicketAgent in a way, you can put the name of
the agent and the types into the constructor.
TicketAgent agentSam = new TicketAgent("Sam", new ExpensiveTicket());
Add setter and getter methods.
And the TicketType needs a float value for the price and maybe a String description
or something like that.
After you are done with this, go back to your main class.
Open a do while loop and set as the loop argument a boolean
value for the user abort, which is false at the beginning and
changes if the user types in the quit command.
Before the loop, instantiate the Agents with the tickets.
Display names and prices. Display tickets. Count together. Ask for abort.
Hope this helps a little.
And sorry for my english, it is not my mother-tongue.
additional:
private boolean userWantsToQuit = false;
private List<TicketAgent> avaibleAgents = new ArrayList<TicketAgent>();
private List<TicketAgent> usedAgents= new ArrayList<TicketAgent>();
private List<TickeType> boughtTickets= new ArrayList<TicketType>();
main(...){
agents.add(new TicketAgent("Sam"));
agents.add(new TicketAgent("wise"));
agents.add(new TicketAgent("gamgee"));
do{
usedAgents.add(askUserForAgent()); //extra static method
boughtTickets.add(askUserForType(agent)); //extra static method
userWantsToQuit = askUserToQuit();//extra static method
}while(!userWantsToQuit);
displayAgentSummary(usedAgents);
displayTicketSummary(boughtTickets);
}
[...]
public static displayAgentSummary(List<TicketAgent> agents)
{
for(TicketAgent agent : agents)
{
System.out.println("Served by: " + agent.getName());
}
}
public static displayTicketSummary(List<TicketType> tickets)
{
float totalPrice = 0;
for(TicketType ticket : tickets)
{
totalPrice =+ ticket.getPrice();
System.out.println("You bought a " + ticket.getName() + " for " + ticket.getPrice()";
}
System.out.println("You bought tickets in total for " + totalPrice + " dollar".
}