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(){}
Related
I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.
I am trying to clean my code up by creating a class specifically for an array of information. It is basically like a storage for variables in case I need them later. Here is what I have so far:
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public static void setGender() {
Scanner input = new Scanner(System.in);
int[] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if(gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while (storeInts[0] < 1) {
storeInts[0]++;
}
}else if(gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
What I'm trying to accomplish here, is if the user types "boy" my code will store 1 in the index [0] of array storeInts[]. If the user types "girl" the index [0] will remain the value of 0.
If I need to refer to the user's gender later on, I want to be able to go back and figure out if they are a "boy" or a "girl" using the array.
I want to be able to called this array from any method within my code. I have already used this array in a complicated way and I would like to find a solution to make it easier.
Here is when I used it:
nameObject.setName(storeInts[0]);
I transferred the index [0] to the setName() method.
Here is the setName() method:
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
}else{
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
As you can see I created another array in the same manner as the previous one, but this one is to store Strings instead. Now back to what I was saying-- the parameter (int x) is the same value as storeInts[0]. This will tell me if the user is male or female. This value is sent to altInit() method when the user decides to try to continue without typing their name in first.
Here is the altInit() method:
public void altInit(int x) {
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")) {
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
When asked if they want to play games, they can type "yes" or "no." If the user types "no" as in they do not want to play games, then the program will print, "Consider this your last warning..." and then continue to the nextName() method in the previous class Gender. This also passes on that index[0] again in the array storedInts[].
Here is the nextName() method:
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
As you can see, if the user is that value of a male (or 1) then the program will print, "What is your name, sir?." If the value is a female (or 0), then the program will print, "What is your name, ma'am?"
This whole time I felt like the stored value of storeInts[0], was just leap frogging around until it was used... I want to prevent this by just creating a class with methods giving me the ability to call any value stored in that array whenever I need it. How do I create an array, store it in a method, and call it when needed?
As someone has requested, here is the entire code:
//Gender class
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public void setGender() {
Scanner input = new Scanner(System.in);
int [] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if (gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while(storeInts[0]<1){
storeInts[0]++;
}
} else if (gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
} else {
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public void nextName(int x){
if (x == 1) {
System.out.println("What is your name, sir?");
}else {
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
//Name class
package com.input;
public class Name extends Gender{
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
public void altInit(int x){
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")){
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
public void setName2() {
String name;
name = input.nextLine();
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You have failed to answer correctly. Try again:");
init();
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
}
How do I create an array, store it in a method, and call it when needed?
This is my first time posting on StackOverflow, but I have visited many times. I am taking a computer science class and I ran into a problem that I have not been able to resolve through research. The assignment is to create a NBATeam class with instance variables and constructors and a NBA client that receives parameters of the names of players from the user and passes them to an array in the first class.
So the problem that I ran into is when I run my program, and I enter player names and pass them to the array, the first array of names are deleted. The names entered into the most recent array are fine, however.
I apologize if my terminology is wrong I am still a newb!
Thank you so much for any help you can give me.
I will insert my code below. My problem is where it says [null]. Also I entered bob for the first team and brian for the second team but bob is in the second team's array.
Please help!
Create NBA team of Heats
Add a player to team Heats? (yes/no)
yes
Enter the name of the player:
bob
Add one more player to Heats?
no
Create NBA team of Spurs
Add a player to team Spurs? (yes/no)
yes
Enter the name of the player:
brian
Add another player to Spurs?
no
***Heat Wins!***
Heats[null]Wins: 4 Loses: 0
Spurs[bob]Wins: 0 Loses: 4
import java.util.*;
public class NBA {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String ifAddPlayer, playerName = null;
//construct Team Heat
System.out.println("Create NBA team of Heats");
NBATeam heats = new NBATeam("Heats");
System.out.println("Add a player to team Heats? (yes/no)");
ifAddPlayer = input.next();
while(ifAddPlayer.equalsIgnoreCase("yes")) {
System.out.println("Enter the name of the player: ");
heats.addPlayer(playerName);
playerName = input.next();
System.out.println("Add one more player to Heats?");
ifAddPlayer = input.next();
}
//construct team Spurs.
System.out.println("Create NBA team of Spurs");
NBATeam spurs = new NBATeam("Spurs");
System.out.println("Add a player to team Spurs? (yes/no)");
ifAddPlayer = input.next();
while(ifAddPlayer.equalsIgnoreCase("yes")) {
System.out.println("Enter the name of the player: ");
spurs.addPlayer(playerName);
playerName = input.next();
System.out.println("Add another player to Spurs?");
ifAddPlayer = input.next();
}
playAGame(heats,spurs);
System.out.println(heats.toString());
System.out.println(spurs.toString());
}
public static void playAGame(NBATeam heats, NBATeam spurs) {
for(int game = 0; game < 7; game++){
double score = Math.random();
if (score < .5) {
heats.winAgame(spurs);
}
else{
spurs.winAgame(heats);
}
if(spurs.nWin()==4 || heats.nWin()==4) {
break;
}
}
if(spurs.nWin()>heats.nWin()) {
System.out.println("***Spurs Win!***");
}
else
System.out.println("***Heat Wins!***");
}
}
import java.util.Arrays;
public class NBATeam {
private String sTeamName;
private int nWin;
private int nLoss;
private int nPlayer;
private String [] playerArray = new String[nPlayer];
public NBATeam(String sTeamName) {
this.sTeamName = sTeamName;
nPlayer=0;
}
public int nWin() {
return nWin;
}
public int nLoss() {
return nLoss;
}
public String getTeamName(){
//gets team's Name
return sTeamName;
}
public String toString() {
return sTeamName + Arrays.toString(playerArray)+ "Wins: " + nWin +
" Loses: " + nLoss;
}
public void lossAgame() {
this.nLoss++;
}
public void winAgame(NBATeam team2) { //To win over the team
nWin++;
team2.setLoss(team2.nLoss()+1);
//teamB.lossAgame();
}
public int getLossNumber() {
return this.nLoss;
}
public void setLoss(int l) {
this.nLoss=l;
}
public int getWinNumber() {
return this.nWin;
}
public void setWin(int w) {
this.nWin=w;
}
public void addPlayer(String player) {
String temp[] = playerArray;
playerArray = Arrays.copyOf(temp, temp.length+1);
playerArray[nPlayer] = player;
nPlayer++;
}
public String[] getPlayerArray() {
return playerArray;
}
public void setPlayerArray(String[] playerArray) {
this.playerArray = playerArray;
}
}
You start with an initial value of null in playerName, and then you add the playerName before getting the value. This,
heats.addPlayer(playerName);
playerName = input.next();
is reversed. It should be
playerName = input.next();
heats.addPlayer(playerName);
And, you were consistent. This,
spurs.addPlayer(playerName);
playerName = input.next();
is likewise reversed. And should be
playerName = input.next();
spurs.addPlayer(playerName);
I would suggest you limit the visibility of your variables. If you had
String playerName = input.next();
heats.addPlayer(playerName);
it would limit the possibility of adding the player before you set it.
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;
}
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.