So, I'm working on a coding assignment and I've reached an impasse. Here is the feedback I received from my professor and afterwards, I'll attach the code I've been working on and further explain the issue:
Thank you for reaching out. It looks good! The only thing I would suggest is adding high level comments throughout your code and testing the set() methods on the Team objects in your MainTeamClass.java program to ensure that the set() mutator methods work as intended. Call the set() method with a test value and then call the get() method to see if it is the same value.
Here is a copy of the code:
public class Team
{
private String team;
private int points;
private double average;
public Team()
{
team = " Default";
}
public Team(String startTeam, int startPoints, double startAverage)
{
team = startTeam;
points = startPoints;
average = startAverage;
}
public String getTeam()
{
return team;
}
public int getPoints()
{
return points;
}
public double getAverage()
{
return average;
}
public void setTeam(String newTeam)
{
team = newTeam;
}
public void setPoints(int newPoints)
{
if (newPoints >= 0)
{
points = newPoints;
}
}
public void setAverage(double newAverage)
{
if (newAverage >= 0.0)
{
average = newAverage;
}
}
}
And the Main class:
public class MainTeamClass { public static void main(String[] args)
{
Team sanfran = new Team();
String sanfranTeam = sanfran.getTeam();
int sanfranPoints = sanfran.getPoints();
double sanfranAverage = sanfran.getAverage();
System.out.println(" The team name is:" + sanfran.getTeam()
+ "\n The number of points earned equals " + sanfran.getPoints()
+ "\n The average season score is:" + sanfran.getAverage());
Team cowboys = new Team("Dallas Cowboys", 36, 43.5);
String cowboysTeam = cowboys.getTeam();
int cowboysPoints = cowboys.getPoints();
double cowboysAverage = cowboys.getAverage();
System.out.println("\n The team name is: " + cowboys.getTeam()
+ "\n The number of points earned equals " + cowboys.getPoints()
+ "\n The average season score is: " + cowboys.getAverage()); } }
Based on this code, how would I go about testing the set() method and the get() method? Can someone explain how to do so and also provide an example? It wasn't in the chapter for this week in class and I've searched the web for some assistance but to no avail, so I would appreciate as much feedback as possible. Thank you in advance!
"Call the set() method with a test value and then call the get() method to see if it is the same value.": means that the the value passed to the set method is the same value that has to be returned from the get method, something like this:
Team team = new Team ();
String test = "stringForTest";
team.setTeam(test);
if(!team.getTeam().equals(test)) {
System.out.println("Problem with set/get method!");
}
You can different methods, one of them assertion and run using java -ea <program_name>
enable assertion
public class MainTeamClass {
public static void main(String[] args) {
Team cowboys = new Team();
cowboys.setTeam("Dallas Cowboys");
String cowboysTeam = cowboys.getTeam();
assert cowboysTeam == "Dallas Cowboys" : "cowboysTeam Not valid";
cowboys.setPoints(36);
int cowboysPoints = cowboys.getPoints();
assert cowboysPoints == 36 : "cowboysPoints Not valid";
cowboys.setAverage(43.5);
double cowboysAverage = cowboys.getAverage();
assert cowboysAverage == 43.5 : "cowboysAverage Not valid";
}
}
Related
I'm making a solar system model that uses takes different solar systems and sets of planets through the use of classes. I've chosen to use an arraylist to store each object of a planet within the solar system although am now struggling to output the data in a suitable format.
The format i am looking for in the toString() method is 'Planet X has a mass of A Earths, is BAU from its star, and orbits in C years: could be habitable? D'
I have attempted using for loops to print each planet however don't believe this is the correct way as a return will cause the loop to stop. Many thanks
SolarSystem.java
import java.util.ArrayList;
public class SolarSystem {
private String systemName;
private double systemLuminosity;
public SolarSystem(String name, double luminosity) {
this.systemName = name;
this.systemLuminosity = luminosity;
}
ArrayList<Planet> list = new ArrayList<>();
public void addPlanet(String name, double mass, double distance) {
list.add(new Planet(name, mass, distance, systemLuminosity));
}
public void planetProperties() {
}
public String toString() {
System.out.println(list.size());
String results = "+";
for (Planet planet : list) {
results += planet.getName(); //if you implement toString() for Dog then it will be added here
}
return results;
}
}
Planet.java
public class Planet {
private String planetName;
private double planetMass;
private double distanceFromStar;
private double orbitalPeriod;
private String isHabitable;
public Planet(String name, double mass, double distance, double systemLuminosity) {
setName(name);
setMass(mass);
setDistanceFromSun(distance);
setOrbitalPeriod(distance);
setIsHabitable(mass, distance, systemLuminosity);
}
public void setName(String name) {
planetName = name;
}
public String getName() {
return planetName;
}
public void setMass(double mass) {
planetMass = mass;
}
public double getMass() {
return planetMass;
}
public void setDistanceFromSun(double distance) {
distanceFromStar = distance;
}
public double getDistanceFromStar() {
return distanceFromStar;
}
public void setOrbitalPeriod(double distance) {
orbitalPeriod = Math.sqrt(distance*distance*distance);
}
public double getOrbitalPeriod() {
return orbitalPeriod;
}
public void setIsHabitable(double mass, double distance, double luminosity) {
if (mass >= 0.6 && mass <= 7.0) {
if ((distance >= 0.75 * Math.sqrt(luminosity)) && (distance <= 2.0 * Math.sqrt(luminosity))) {
isHabitable = "yes";
} else {
isHabitable = "no";
}
} else {
isHabitable = "no";
}
}
public String getIsHabitable() {
return isHabitable;
}
}
Main.java
public class Main {
public static void main(String[] args) {
//Create our solar system
SolarSystem ourSystem = new SolarSystem("Our System",1.0);
//Add planets in our solar system
ourSystem.addPlanet("Mercury", 0.055, 0.387);
ourSystem.addPlanet("Venus", 0.815, 0.723);
ourSystem.addPlanet("Earth", 1.0, 1.0);
ourSystem.addPlanet("Mars", 0.107, 1.52);
ourSystem.addPlanet("Jupiter", 317.8, 5.20);
ourSystem.addPlanet("Saturn", 95.2, 9.58);
ourSystem.addPlanet("Uranus", 14.5, 19.20);
ourSystem.addPlanet("Neptune", 17.1, 30.05);
System.out.println(ourSystem.toString());
}
}
You need to implement a toString() method inside your Planet class, for example:
class Planet {
private String planetName;
private double planetMass;
private double distanceFromStar;
private double orbitalPeriod;
private String isHabitable;
#Override
public String toString() {
return String.format(
"Planet %s has a mass of %f Earths, is %f from its star, and orbits in %f years: could be habitable? %s%n",
this.planetName, this.planetMass, this.distanceFromStar, this.orbitalPeriod, this.isHabitable);
}
}
Then inside your SolarSystem class you can create a list with something like this, you already have that part almost correct but I've changed getName to toString:
#Override
public String toString() {
StringBuilder buf = new StringBuilder();
for (Planet planet : list) {
buf.append(planet);
}
return buf.toString();
}
If you want to print out a description for the entire solar system (the entire array list of planets), I would suggest to implement the toString() method inside the Planet class. Doing so will allow you to simply iterate over the Planets array list, and just call planet.toString(). Encapsulating the logic for a singular planet inside the Planet class is the way to go.
You have to redefine toString in the Planet class and replace the toString of SolarSystem to use it.
public class Planet {
...
public String toString() {
return "Planet " + planetName + " has a mass of " + planetMass +
" Earths, is BAU from its star, and orbits in " + orbitalPeriod +
" years: could be habitable? " + isHabitable;
}
}
public class SolarSystem {
...
public String toString() {
String results = "";
for (Planet planet : list) {
results += planet.toString() + "\n"; // Use the toString of planet and add a new line
}
return results;
}
}
Note: for performance reasons as commented by oleg it is preferable to use a StringBuilder to concatenate strings. In this situation where you have few items and the problem is not related to the performances you can leave the + operator.
Growing your java knowledge you will find useful functions like String.join:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
That will help you mantaining your code simpler and cleaner replacing this:
public String toString() {
String results = "";
for (Planet planet : list) {
results += planet.toString() + "\n"; // Use the toString of planet and add a new line
}
return results;
}
with
public String toString() {
return String.join("\n", list);
}
but my tip is to start from the basis of java before trying to use more advanced functions. Otherwise you will use them without knowing what happens behind the scenes
To echo other posters, you need to define a custom toString() method in the planet class first. Please see my suggestions below. They are presented as pseudo-code typed on the fly, not actual code (for there might be a few things here and there that might not compile.)
But the pseudo-code should give an idea for a possible solution. Hit me up if you still have questions.
Based on your requirements:
The format i am looking for in the toString() method is 'Planet X has
a mass of A Earths, is BAU from its star, and orbits in C years: could
be habitable? D'
Your Planet.toString method could look as follows (this is pseudo-code, not bound to be compilable, but you get the gist of it.)
public class Planet {
/* your class as it is, with the
* addition of a possible toString
* implementation */
public String toString(){
return String.format(
"Planet: %s, " +
"mass: %f, " +
"distance: %f, " +
"orbital period: %f, " +
"habitable: %b"
this.getName(),
this.getMass(),
this.getDistanceFromStar(),
this.getOrbitalPeriod(),
this.getIsHabitable());
}
}
Then, your SolarSystem class should have an appropriate toString method that loops over the collection of planets in it. Your original toString method had the right idea, I'm just extending the notion.
public class SolarSystem {
/*
Your solar system class plus some changes
...
*/
public String getName(){
return this.systemName;
}
public String getLuminosity(){
return this.systemLuminosity;
}
public int getPlanetCount(){
return this.list.size();
}
public String toString() {
final StringBuffer buffer = new StringBuffer();
buffer.append(
String.format("System: %s\nLuminosity: %f\nPlanet Count:%d\n",
this.getName(),
this.getLuminosity(),
this.getPlanetCount()
)
);
for (final Planet planet : list) {
buffer.append('\t')
.append(planet.getString())
.append('\n');
}
return buffer.toString();
}
}
Now, I'm a bit confused with this:
I have attempted using for loops to print each planet however don't
believe this is the correct way as a return will cause the loop to
stop. Many thanks
A return statement will stop a loop if the return is done within the loop.
A return statement done within a function called within the loop will not end the loop.
That is, a return only ends the function that makes the return call, not functions up in the call chain.
Compare this
for(Foo f : fooList){
if(something){
return; // this will stop the loop
}
}
With this
for(Foo f : fooList){
if(something){
callThisFu(); // the return within callThisFu *will not* exit the loop
}
}
Hope this clear this up.
As part of my learning process, I am creating a small program in Java that would help a fictitious company help in selling burgers.
In the code below, I created class for a burger and added options to add additions to that burger (like lettuce, carrots etc).
The problem I am facing is how to go about checking each extra addition to the base hamburger (base hamburger meaning only bun and meat) without using if-else too much. One way I tried (you can also see that in code) is by assigning each addition a number, for example, 1 to lettuce, 2 carrots and so on. By adding 1 and 2 we get 3; we can look for 3 to find whether lettuce and carrot are added so that we can calculate price. I did this with other options too.
Some problems arose, however:
There are some cases when a number generated by adding is created twice from different additions this can be tackled somewhat by multiplying the number with some number or by adding 1 as I create more edge cases.
My main problem, by creating such cases, is that it would require a lot of if-else statements, which I am trying to avoid in order to effectively code what i need.
Please suggest if there is any other way to do it. Please note code is not yet complete since I didn't want to create more if-else statements (in hamburger class; method cal_price) to check for additions, but it is enough to fully understand the nature of code. Code is given below:
public class Main {
public static void main(String[] args) {
Breadroll breadroll_type = new Breadroll("Sesame Seed Bun");
meat meat_type = new meat("Beef");
Hamburger my_burger = new Hamburger("Hamburger",breadroll_type,meat_type);
my_burger.select_items(1,2,3,4);
my_burger.cal_price();
my_burger.getBreadroll_type();
my_burger.getMeat_type();
}
}
public class Breadroll {
private String breadroll_type;
public Breadroll(String breadroll_type) {
this.breadroll_type = breadroll_type;
}
public String getBreadroll_type() {
return breadroll_type;
}
}
public class meat {
private String meat_type;
public meat(String meat_type) {
this.meat_type = meat_type;
}
public String getMeat_type() {
return meat_type;
}
}
public class Hamburger {
private String name;
Breadroll breadroll_type;
meat meat_type;
private double base_price; //Price without addons
private int lettuce;
private int carrot;
private int tomato;
private int cheese;
private int hot_sauce;
private int mustard;
private int total_select;
public Hamburger(String name, Breadroll breadroll_type, meat meat_type) {
this.name = name;
this.breadroll_type = breadroll_type;
this.meat_type = meat_type;
this.base_price = 2.75;
}
public void select_items(int lettuce, int carrot, int tomato, int cheese) {
this.lettuce = lettuce;
this.carrot = carrot;
this.tomato = tomato;
this.cheese = cheese;
this.total_select = lettuce + carrot + tomato + cheese;
}
public void cal_price()
{
double final_price;
double lettuce_price = 0.50;
double carrots_price = 0.60;
double tomatos_price = 0.70;
double cheese_price = 0.85;
if(total_select == 0) {
System.out.println("Order Placed : Hamburger with no additions " + getBase_price() + "$");
}
else if (total_select == 1) {
final_price = getBase_price() + lettuce_price;
System.out.println("Order Placed : Hamburger with all lettuce " + (float) final_price + "$");
}
else if (total_select == 2) {
final_price = getBase_price() + carrots_price;
System.out.println("Order Placed : Hamburger with all carrot " + (float) final_price + "$");
}
else if (total_select == 3) {
final_price = getBase_price() + tomatos_price;
System.out.println("Order Placed : Hamburger with all tomato " + (float) final_price + "$");
}
else if (total_select == 4) {
final_price = getBase_price() +cheese_price;
System.out.println("Order Placed : Hamburger with all cheese " + (float) final_price + "$");
}
else if (total_select*100 == 1000) {
final_price = getBase_price() + lettuce_price + carrots_price + tomatos_price + cheese_price;
System.out.println("Order Placed : Hamburger with all additions " + (float) final_price + "$");
}
}
public String getName() {
return name;
}
public void getBreadroll_type() {
System.out.println(breadroll_type.getBreadroll_type());
}
public void getMeat_type() {
System.out.println(meat_type.getMeat_type());
}
public double getBase_price() {
return base_price;
}
public int getLettuce() {
return lettuce;
}
public int getCarrot() {
return carrot;
}
public int getTomato() {
return tomato;
}
public int getCheese() {
return cheese;
}
}
Your implementation of a ‘hamburger’ object seems to be a bit over-complicated. Usually object oriented programming to represent actual, physical objects should choose the simplest, most atomic attributes as possible to avoid situations like this. A hamburger either does or does not have lettuce. It either does or does not have tomato. My recommendation is to have separate Boolean variables for each topping, or a Boolean array representing the toppings if you’d prefer. Then, add a get_price() method to your Hamburger which has a single block of if statements for calculating your price. If you really want to get into OOP, each topping could be an object with a price, which you append to a Toppings ArrayList on your hamburger. Then, your get_price() method would use a for-each to total all the prices of your Topping objects, as well as your hamburger’s price attribute. This method might be better if you want multiple quantities of the same topping. This is the fun part of programming - you can choose the implementation that makes the most sense to you and try it out!
Made a hamburger with name, breadtype, meattype and added the extra's later on, you can make seperate methods for the breadtype and meat as well. In the extra methods we calculate the extra price beforehand so calling getPrice() sums up all the extras with chosen bread/meat type. There are other ways to do this but this way you'll also have an example of a contract and switch statement. Removed a few ingredients but you get the point.
Also take look at the naming conventions how they are different from yours.
class HamburgerContract {
// Specify your constants in this class so all classes are able to communicate with the same values
// Change the name to something shorter like HBC for easier reference, ie HBC.BR_TYPE_SESAM
public static final int BR_TYPE_SESAM = 1;
public static final int BR_TYPE_HONEY = 2;
public static final int MEAT_TYPE_COW = 1;
public static final int MEAT_TYPE_CHICKEN = 2;
}
public class Hamburger {
public static void main(String[] args) {
// Made a hamburger with name, breadtype, meattype and added the extra's later on
// You can make seperate methods for the breadtype and meat as well
// In the extra methods we calculate the extra price beforehand
// So calling getPrice() sums up all the extras with chosen bread/meat type
// There are other ways to do this but this way you'll also have an example of a contract and switch statement
// Removed a few ingredients but you get the point
Hamburger myHamburger = new Hamburger("Varadero Burger", HamburgerContract.BR_TYPE_SESAM, HamburgerContract.MEAT_TYPE_CHICKEN, 2.50);
myHamburger.addCarrot();
myHamburger.addLettuce();
myHamburger.removeCarrot();
System.out.print("The price of your " + myHamburger.getName() + "is $ " + myHamburger.getPrice());
}
private String burgerName;
private int breadrollType;
private int meatType;
private boolean lettuce;
private boolean carrot;
private double basePrice;
private double extraPrice;
public Hamburger(String burgerName, int breadrollType, int meatType, double basePrice) {
this.burgerName = burgerName;
this.breadrollType = breadrollType;
this.meatType = meatType;
this.basePrice = basePrice;
this.extraPrice = 0;
this.lettuce = false;
this.carrot = false;
}
public void addLettuce() {
// extra check if lettuce is not already added, so you wont add to the price twice
// same goes for removing the lettuce or the carrot methods
if (!lettuce) {
letuce = true;
extraPrice += 0.25;
}
}
public removeLettuce() {
if (lettuce) {
letuce = false;
extraPrice -= 0.25;
}
}
public void addCarrot() {
if (!carrot) {
carrot = true;
extraPrice += 0.20;
}
}
public void removeCarrot() {
if (carrot) {
carrot = false;
extraPrice -= 0.20;
}
}
public String getName() {
return burgerName;
}
public double getPrice() {
switch (breadrollType) {
case HamburgerContract.BR_TYPE_HONEY: extraPrice += 0.25; break;
case HamburgerContract.BR_TYPE_SESAM: extraPrice += 0.50; break;
}
switch (meatType) {
case HamburgerContract.MEAT_TYPE_COW: extraPrice += 0; break;
case HamburgerContract.MEAT_TYPE_CHICKEN: extraPrice += 0.50; break;
}
return basePrice + extraPrice;
}
}
You don't need to use conditional statements at all, just multiply the price of each item by its price:
final_price = getBase_price()
+ lettuce_num * lettuce_price
+ carrots_num * carrots_price
+ tomatos_num * tomatos_price
+ cheese_num * cheese_price;
In your set method you should then set the number/amount of items (e.g., lettuce) and not 1 == lettuce and 2 == xxx :
my_burger.select_items(5,0,0,0); // 5 lettuce, 0 all other
my_burger.select_items(1,0,0,90); // 1 lettuce, 90 cheese, 0 all other
Putting it all together (minified):
public class Main {
public static void main(String[] args) {
Hamburger my_burger = new Hamburger("Hamburger");
my_burger.select_items(
100, // 100 lettuce
0, // 0 carrot
2, // 2 tomato
1); // 1 cheese
my_burger.cal_price();
}
}
public class Hamburger {
private String name;
private double base_price = 2.75;
private int lettuce;
private double lettuce_price = 0.50;
private int carrot;
private double carrots_price = 0.60;
private int tomato;
private double tomatos_price = 0.70;
private int cheese;
private double cheese_price = 0.85;
public Hamburger(String name) {
this.name = name;
}
public void select_items(int lettuce, int carrot, int tomato, int cheese) {
this.lettuce = lettuce;
this.carrot = carrot;
this.tomato = tomato;
this.cheese = cheese;
}
public void cal_price()
{
double final_price = getBase_price()
+ lettuce * lettuce_price
+ carrots * carrots_price
+ tomato * tomatos_price
+ cheese * cheese_price;
// TODO print price
}
}
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
Recently, I've learned something: I have no idea how to use toString methods.(If you've seen my last question, you'll get a prime example.)
Anyways, I was going through some unfinished programs of mine from an Intro to Java class I took last year and this one I just cannot finish. My effort to become a better programmer has faced the ultimate challenge: toString methods.
The basic overview is that I had to write a 'Grocery' store program where the ShoppingCart class was an ArrayList of Grocery Objects.
There's just one problem- when I run the program I get
Grocery.ShoppingCart#2eeb3c84
My old enemy, the toString() looks like it is required.
The output I should be getting is this:
[Tomatoes: 2.76 $1.39, Mac & Cheese: 6.0, $0.89]
now if I print out the Cart ArrayList (System.out.println(Cart)) I get this:
[Tomatoes, 2.76, $1.39, Mac & Cheese, 6.0, $0.89]
Exactly the output I should be getting.
How does this happen? How can I fix this?
When I print out the Cart Arraylist, I get the output I want (I still get the "Grocery.ShoppingCart#). I have to find some way to replace the "Grocery.ShoppingCart#[etc.]" with the ArrayList.
Anybody have any ideas?
Thanks!
-Chris
Bits of the ShoppingCart class:
ArrayList<Grocery> Cart = new ArrayList<Grocery>();
int size = Cart.size();
double tot = 0.0;
public ShoppingCart(){
}
...
public void printReceipt() {
Grocery temp = new Grocery();
double pr = 0.0;
double qu = 0.0;
String n = "";
String con = "IF YOU SEE ME SOMETHING IS WRONG!";
double gr = 0.0;
for(int k = 0; k < size; k++){
temp = Cart.get(k);
n = temp.getName();
qu = temp.getQuan();
pr = temp.getPrice();
tot = qu * pr;
con = n + ":" + " " + qu + ", " + pr + "\t\t Total: $" + tot;
}
System.out.println("====RECIEPT====");
System.out.println("Grand Total:\t" + "$" + totalPr());
}
Grocery Class Printing out ShoppingCart
public static void testShoppingCartClass ()
{
System.out.println ("Testing ShoppingCart class\n");
ShoppingCart myCart = new ShoppingCart();
System.out.println (" ShoppingCart using default constructor: ");
System.out.println ("\t" + myCart);
myCart.addItem (new Grocery("Tomatoes", 2.76, 1.39));
myCart.addItem (new Grocery("Mozzarella", 0.95, 4.59));
myCart.addItem (new Grocery("Mac & Cheese", 6, 0.89));
System.out.println ("\n ShoppingCart after adding three items: ");
System.out.println ("\t" + myCart);
myCart.removeItem (1);
System.out.println ("\n ShoppingCart after removing an item: ");
System.out.println ("\t" + myCart);
System.out.println ("\n\nPrinting receipt: \n");
myCart.printReceipt();
System.out.println ("\n\nDone testing ShoppingCart class\n\n");
}
You can override toString to return whatever you want. In your case, it looks like you want to do:
class ShoppingCart {
ArrayList<Grocery> cart;
...
#Override
public String toString() {
return cart.toString();
}
}
Java's default toString() method on any object will print out what you're seeing ("Grocery.ShoppingCart#[etc.]"). This is the Class with the object's hash code appended to the end of it.
From what I see in that output, you're calling .toString() on an instance of the ShoppingCart class which is why you're getting that output.
In order for that class to print out the contents of the ArrayList - Cart, which is a member of that class, you will need to override the toString() method of that class to print the contents of the ArrayList. Once it is overridden, your implementation of the toString() will be called rather than the default.
public String toString() {
// return the string that you want.
}
toString() is called on shoppingCart when you call System.out.println(shoppingCart) in order to retrieve the string to print.
Yes, you'll need a toString() on your ShoppingCart.
If I understand what you're trying to do though, may I suggest going with a more conventional Java bean approach? Here's a simplistic view.
Bean with getter and setters. A better name for this might be Item. You can change the types as needed as well.
public class Grocery {
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private BigDecimal quantity;
private BigDecimal price;
private String name;
#Override
public String toString() {
return "Grocery{" +
"quantity=" + quantity +
", price=" + price +
", name='" + name + '\'' +
'}';
}
}
And your cart:
public class ShoppingCart {
List<Grocery> contents;
public void initialize() {
contents = new ArrayList<Grocery>();
}
public void addItem(Grocery item) {
contents.add(item);
}
public void removeItem(Grocery item) {
boolean wasRemoved = contents.remove(item);
if (!wasRemoved) {
System.out.println("Item not found in cart: " + item);
}
}
public List<Grocery> getContents() {
return contents;
}
#Override
public String toString() {
return "ShoppingCart{" +
"contents=" + contents +
'}';
}
}
And some class to run it:
public class CartRun {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.initialize();
Grocery item = new Grocery();
item.setName("Tomatoes");
item.setPrice(BigDecimal.valueOf(2));
item.setQuantity(BigDecimal.valueOf(3));
cart.addItem(item);
System.out.println("Item="+item);
System.out.println("Cart="+cart);
}
}
Output:
Item=Grocery{quantity=3, price=2, name='Tomatoes'}
Cart=ShoppingCart{contents=[Grocery{quantity=3, price=2, name='Tomatoes'}]}
Also, stay away from capital letters (e.g., "Cart") for variable names because it looks like a static method call by convention.
i already have the athelete class and i just dont know how to go about the rest of the problem ive been trying to do things that havent work at all but heres what i have for now. im still a beginner this is my first semester taking java so i may not understand some of the things you guys will add so if u can please explain.
This is what they are asking for me to do.
Add a static method to the class which takes an array of Athletes as its argument, and returns the total number of medals won by all athletes stored in the array. test in method.
package homework;
import java.util.Arrays;
public class Athlete {
private String name; // the name of the athlete
private String sport; // the sport the athlete does
private int numMedals; // the number of medals that the athlete has won
// constructor
public Athlete(String n, String s, int num) {
name = n;
sport = s;
numMedals = num;
}
// getters and setters for all instance variables
// (also called accessors and mutators)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public int getNumMedals() {
return numMedals;
}
public void setNumMedals(int numMedals) {
this.numMedals = numMedals;
}
/* Returns a String with information about the athlete.
*/
public String toString() {
return name + " does " + sport + " and has won " + numMedals + " medal(s).";
}
public static void AthMedals(int[][]numMedals){
for(int i = 0; i < numMedals.length;i++){
int total = 0;
for(int j = 0; j < numMedals.length; i++);
total = numMedals.getNumMedals();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Athlete SA = new Athlete("Socrates","Baseball",5);
Athlete CC = new Athlete("Cesar","Baseball",3);
Athlete JA = new Athlete("Juan","Soccer",2);
System.out.println(SA);
System.out.println(CC);
System.out.println(JA);
System.out.println("SA has " +SA.getNumMedals()+ " medals.");
}
}
}
The assignment is to write a method like
public static int sumOfAllMedals(Athlete[] all)
which returns all[0].numMedals + all[1].numMedals + ... + all[n].numMedals.
I assume AthMedals is your attempt at doing this, but it's in fact only consuming processing power while not doing anything.
I'm not gonna do your homework for you, but here's a hint:
public static int sumOfAllMedals(Athlete[] all)
{
int total = 0;
// For every Athlete in `all`, add the number of medals (s)he's won
// Should be four lines at most ;)
return total;
}
The static method have to iterate the array and add each medals to a final return variable.
static public int totalMedals(Athlete[] athelte) {
int totalMedals = 0;
for(int i=0;i<athelte.length;i++) {
totalMedals += athelte[i].numMedals;
}
return totalMeadls;
}
I am trying to read in a figure for a brokers earnings for quarter one of the year.I want to ensure that 0 or less can not be entered but when I enter 0 it just takes it in anyway and does not throw the exception?
What am I doing wrong?Any help would be greatly appreciated.
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException("new quarter must be > 0.0");
}
Ok heres my whole assignment code
import java.util.Scanner;
public class Broker {
//(a) declare instance variables
private String department, firstName, lastName;
private double quarter1, quarter2, quarter3, quarter4;
//(b) Access methods for instance variables
public void setDepartmentName(String newName)
{
department=newName;
}
public String getDepartment ()
{
return department;
}
//set and get methods for first name
public void setFirstName (String newFirstName)
{
firstName=newFirstName;
}
public String getFirstName ()
{
return firstName;
}
//set and get methods for last name
public void setLastName(String newLastName)
{
lastName=newLastName;
}
public String getLastName ()
{
return lastName;
}
//set and get methods for Quarter 1
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException(
"new quarter must be > 0.0");
}
public double getQuarter1()
{
return quarter1;
}
//set and get methods for Quarter 2
public void setQuarter2(double newQuarter2)
{
quarter2 = newQuarter2;
}
public double getQuarter2 ()
{
return quarter2;
}
//set and get methods for Quarter 3
public void setQuarter3(double newQuarter3)
{
quarter2 = newQuarter3;
}
public double getQuarter3 ()
{
return quarter3;
}
//set and get methods for Quarter 4
public void setQuarter4(double newQuarter4)
{
quarter4 = newQuarter4;
}
public double getQuarter4 ()
{
return quarter4;
}
//(c) class variable annualbrokerage total and two access methods
private static double brokerageTotal;
public void setbrokerageTotal(double newBrokerageTotal)
{
newBrokerageTotal=brokerageTotal;
}
//(c) constructor to initialise instance variables department,firstname and lastname
public Broker (String dept, String first, String last )
{
department = dept;
firstName = first;
lastName = last;
}
// (d) constructor to initialise all instance variables from (a)
public Broker (String dept, String first, String last,double q1,double q2,double q3,double q4 )
{
department = dept;
firstName = first;
lastName = last;
quarter1 = q1;
quarter2 = q2;
quarter3 = q3;
quarter4 = q4;
}
// (e) no-argument constructor to initialise default broker instance
public Broker ()
{
department = null;
firstName = null;
lastName = null;
quarter1 = 0;
quarter2 = 0;
quarter3 = 0;
quarter4 = 0;
}
//(f) Method to read in quarters from user
public void readInQuarters ()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt();
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
} //end of read in quarters method
// (g) getBrokerTotal Method to return total trades for 4 quarters
public double getBrokerTotal()
{
//code to calculate broker quarterly totals
double brokerTotal = quarter1 + quarter2 + quarter3 + quarter4;
return brokerTotal;
} //end of getBrokerTotal method
//(e) getBonus method to calculate brokers bonus
public double getBonus()
{
double bonusRate=0;
double bonus=0;
//bonus rate depending on department rate
if("Dublin"==department)
bonusRate=.12;
else if("London"==department)
bonusRate=.15;
else
bonusRate=.10;
bonus = (quarter1 + quarter2 + quarter3 + quarter4)*(bonusRate);
return bonus;
}
//(i) to string method for broker class
public String toString()
{
return String.format(" Name: "+ getFirstName()+"\n Surname: "+getLastName()+"\n Department: "+getDepartment()+"\n Total: "+getBrokerTotal()+"\n Bonus: "+getBonus()+"\n\n");
}//end of toString method
//(i) Static methods to read in broker array and output quarterly totals
//Quarter1 totals method
public static double getQuarter1Total (Broker[]brokerQuarter1Array)
{
double quarter1Total = brokerQuarter1Array[0].getQuarter1()+ brokerQuarter1Array[1].getQuarter1()+ brokerQuarter1Array[2].getQuarter1()+ brokerQuarter1Array[3].getQuarter1()
+ brokerQuarter1Array[4].getQuarter1() + brokerQuarter1Array[5].getQuarter1();
return quarter1Total;
}
//Quarter2 totals method
public static double getQuarter2Total (Broker[]brokerQuarter2Array)
{
double quarter2Total = brokerQuarter2Array[0].getQuarter2()+ brokerQuarter2Array[1].getQuarter2()+ brokerQuarter2Array[2].getQuarter2()+ brokerQuarter2Array[3].getQuarter2()
+ brokerQuarter2Array[4].getQuarter2() + brokerQuarter2Array[5].getQuarter2();
return quarter2Total;
}
//Quarter3 totals method
public static double getQuarter3Total (Broker[]brokerQuarter3Array)
{
double quarter3Total = brokerQuarter3Array[0].getQuarter3()+ brokerQuarter3Array[1].getQuarter3()+ brokerQuarter3Array[2].getQuarter3()+ brokerQuarter3Array[3].getQuarter3()
+ brokerQuarter3Array[4].getQuarter3() + brokerQuarter3Array[5].getQuarter3();
return quarter3Total;
}
//Quarter4 totals method
public static double getQuarter4Total (Broker[]brokerQuarter4Array)
{
double quarter4Total = brokerQuarter4Array[0].getQuarter4()+ brokerQuarter4Array[1].getQuarter4()+ brokerQuarter4Array[2].getQuarter4()+ brokerQuarter4Array[3].getQuarter4()
+ brokerQuarter4Array[4].getQuarter4() + brokerQuarter4Array[5].getQuarter4();
return quarter4Total;
}
// Static method to calculate total brokerage totals for all brokers
public static void setBrokerageTotal (Broker[] brokerTotalsArray)
{
double annualBrokerageTotal= brokerTotalsArray[0].getBrokerTotal() + brokerTotalsArray[1].getBrokerTotal()
+ brokerTotalsArray[2].getBrokerTotal() + brokerTotalsArray[3].getBrokerTotal() + brokerTotalsArray[4].getBrokerTotal() + brokerTotalsArray[5].getBrokerTotal();
}
// Static method to get the total bonuses for all brokers cobined
public static double getBrokerageBonus (Broker [] brokerageBonusTotalArray)
{
double totalBrokerageBonus = brokerageBonusTotalArray[0].getBonus()+ brokerageBonusTotalArray[1].getBonus()+ brokerageBonusTotalArray[2].getBonus()+ brokerageBonusTotalArray[3].getBonus()
+ brokerageBonusTotalArray[4].getBonus() + brokerageBonusTotalArray[5].getBonus();
return totalBrokerageBonus;
}
public static void main(String[]args)
{
//Part-B
///(a) create broker1 with the no argument constructor
Broker broker1=new Broker();
broker1.setDepartmentName("Dublin");
broker1.setFirstName("John");
broker1.setLastName("Wall");
broker1.setQuarter1(12);
broker1.setQuarter2(24);
broker1.setQuarter3(26);
broker1.setQuarter4(17);
System.out.print(broker1);
//(b) create broker2
Broker broker2 = new Broker("London","Sarah","May");
broker2.setQuarter1(8);
broker2.setQuarter2(11);
broker2.setQuarter3(7);
broker2.setQuarter4(9);
System.out.print(broker2);
//(c) create broker3
Broker broker3 = new Broker("London","Ruth","Lavin");
//call read in quarters method
broker3.readInQuarters();
System.out.print(broker3);
//(d) create broker4,broker5,broker6
Broker broker4=new Broker("Dublin","Conor","Smith",21,23,26,31);
Broker broker5=new Broker("Paris","Jerome","Duignan",14,14,17,18);
Broker broker6=new Broker("Paris","Patick","Bateman",23,24,26,35);
//(e) Create broker array
Broker[] brokers;
brokers=new Broker [6];
brokers[0]=broker1;brokers[1]=broker2;brokers[2]=broker3;brokers[3]=broker4;brokers[4]=broker5;brokers[5]=broker6;
//(f) Output second table
String[] headings ={"Dept","Firstname","Surname","Q1","Q2","Q3","Q4","Total","Bonus"};
//loop to print the headings
for (int i = 0; i < headings.length; i++)
{
System.out.print(headings[i]+" ");
}
//print a space under the headings
System.out.println(" \n");
//loop to print the main table plus format specifiers to align the text
for (int i = 0; i < 5; i++)
{
System.out.printf("%-7s %-13s %-11s %-6s %-6s %-6s %-6s %-10s %.1f \n\n",brokers[i].getDepartment(), brokers[i].getFirstName(),brokers[i].getLastName(),brokers[i].getQuarter1(),brokers[i].getQuarter2(),brokers[i].getQuarter3(),brokers[i].getQuarter4(),brokers[i].getBrokerTotal(),brokers[i].getBonus());
}
// console printout for quarterly totals
System.out.printf("%33s \n","Quarterly ");
System.out.printf("%29 %9s %6s %6s %6s %6s \n","Total ",getQuarter1Total(brokers),getQuarter2Total(brokers),getQuarter3Total(brokers),getQuarter4Total(brokers),getBrokerageBonus(brokers));
} //end of method main
} //end of class broker
er
You aren't using your setters. The problem is here
public void readInQuarters () {
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt(); // <-- Use your setters!
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
// should be,
setQuarter1(input.nextInt()); // and so on... although I will point out, you should
// be reading double(s) apparently.
}
Hello Friend I have give a suggestion which is am also use in our project
call this method before submitting the value. And if return true then update data other wise show mgs in validate method of where from call update
boolean validate() {
int c = Integer.parseInt(txtFieldSetupTopElevation.getText().toString().trim());
if (c <= 0) {
// Here use code for show msg error or information
// return true if value is greater than 0 other wise return else
return false;
}
}
Sandeep