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 8 years ago.
Improve this question
Hey guys I just had a question about toString. On a previous test my professor had this overrided method for toString that was similar to this method which I'm testing:
public String toString()
{
String s="";
s+="units: " + units;
s+="\n";
s+="owner: " +owner;
return s;
}
This method is is inside the class Residential which inherits from a base class Construction. Anyways, this mirrors a problem I had on a test where I would try to do say:
Residential R1 = new Residential();
R1.toString();
I thought R1.toString(); would display, which I put on the test, but obviously it was marked wrong and it doesn't.
So now I'm going over the problem and how to correct it. I tried doing say:
System.out.println(R1.toString());
but it's still giving me some weird output like "Residential#5c538b31". Why does it not overriden?
edit: The whole residential class, I'm aware it's not overridden, now but it wasn't annoted with a #Override by the professor in his code either so I assumed it wasn't needed.
public class Residential extends Construction {
private int units;
private String owner;
Residential ()
{
super();
units = 0;
owner = "Unknown";
}
Residential (String n, int y, double a, int u, String o)
{
super (n,y,a);
units = u;
owner = o;
}
public int getUnits()
{
return units;
}
public void setUnits(int u)
{
units = u;
}
public String getOwner()
{
return owner;
}
public void setOwner(String o)
{
owner = o;
}
public void display()
{
System.out.println("Name: " + getName() + " Year: " + getYear() + " Area: " + getArea() + " Number of Units: " + getUnits() + " Owner: " + getOwner());
}
public boolean isEqual (Residential r)
{
if (this.getName() == r.getName() && this.getYear() == r.getYear() && this.getArea() == r.getArea() && this.units == r.units && this.owner == r.owner)
{
return true;
}
return false;
}
public String toString()
{
String s="";
s += "the units is: " + units;
s += "\n";
s += "Owner: " + owner;
return s;
}
edit 2: Added construction class
public class Construction {
private String buildername;
private int year;
private double area;
Construction()
{
buildername = "Unknown";
year = 0;
area = -1;
}
Construction(String b, int y, double a)
{
buildername = b;
year = y;
area = a;
}
//Mutators
public void setName(String n)
{
buildername = n;
}
public void setYear(int y)
{
year = y;
}
public void setArea (double a)
{
area = a;
}
//Accessors
public String getName()
{
return buildername;
}
public int getYear()
{
return year;
}
public double getArea()
{
return area;
}
public void display()
{
System.out.println("Builder's Name: " + getName() + " Year: " + getYear() + " Area: " + getArea());
}
public boolean isEqual(Construction c)
{
if (this.buildername == c.buildername && this.year == c.year && this.area == c.area)
{
return true;
}
return false;
}
}
but it's still giving me some weird output like "Residential#5c538b31". What am I doing wrong?
This means that your version of the Residential class does not correctly override the toString() method.
To fix this, you need to give your class a proper toString override. I would also give the method an #Override annotation to be sure that it's truly overriding the method.
You also state:
On a previous test my professor had this overrided method for toString that was similar to this method which I'm testing...
... and yet you have not shown us the method that you're "testing". Perhaps you want to do this.
Edit
Regarding your posted code, that code is not what has produced the output that you've posted. Perhaps you need to refresh or restart your IDE, but the output could not possibly come from the posted code.
As an aside, your Residential toString() method should also call its parent class's toString() method in its method body, since the String returned should be part of Residential's String.
Related
Im trying to make a comparison operator that checks if the content of 2 objects are the same, in this instance the Object is called Game and has atributes releaseJaar and naam.
The first call of the method .equals() works just fine but when i try to call it a second time it says it cant resolve the method?
public boolean equals(Object andereObject){
if (andereObject instanceof Game) {
if (((Game) andereObject).getNaam().equals(naam) && ((Game) andereObject).getReleaseJaar().equals(releaseJaar)){
return true;
}
}
else {
return false;
}
}
I dont know what i'm doing wrong here :(
Ps: might be multiple things since i just started on the subject of 1 to many relations.
public class Game {
private String naam;
private int releaseJaar;
private double nieuwprijs;
private int ditJaar = LocalDate.now().getYear();
public Game(String nm, int rJ, double nwpr){
this.naam = nm;
this.releaseJaar = rJ;
this.nieuwprijs = nwpr;
}
public String getNaam(){
return naam;
}
public double getReleaseJaar(){
return releaseJaar;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public double huidigeWaarde(){
int jaarVerschil = ditJaar - releaseJaar;
double nieuweWaarde = nieuwprijs;
for (int i = 0; i < jaarVerschil; i++){
nieuweWaarde = nieuweWaarde * 0.7;
}
return nieuweWaarde;
}
//De werkende functie moet nog gemaakt worden
public boolean equals(Object andereObject){
if (andereObject instanceof Game) {
if (((Game) andereObject).getNaam().equals(naam) && ((Game) andereObject).getReleaseJaar().equals()){
return true;
}
}
else {
return false;
}
}
#Override
public String toString() {
return "Game{" +
"naam='" + naam + '\'' +
", releaseJaar=" + releaseJaar +
", nieuwprijs=" + nieuwprijs +
'}';
}
}
THis is the code, just for you to reference when you're curious about what I'm trying to accomplish:
import java.util.EmptyStackException;
public class TicketMain {
public static void main(String[] args) {
// Create a Student Ticket
StudentTicket t1 = new StudentTicket(100,true);
t1.setPromotionCode("KEXP call-in winner");
System.out.println(t1);
// Generate a general ticket
Ticket t2 = new Ticket(55, 40);
System.out.println(t2);
// Generate a student ticket
StudentTicket t3 = new StudentTicket(90,false);
t3.setPromotionCode("KEXP call-in winner");
System.out.println(t3);
// Check for equality
System.out.println("Ticket t1 and Ticket t2 are equal: " + t1.equals(t2)); // Should return false
System.out.println("Ticket t1 and Ticket t3 are equal: " + t1.equals(t3)); // Should return true
// Total tickets generated
System.out.println("Total Tickets generated so far: " + Ticket.getTicketCount());
}
}
class Ticket {
private double price;
private int daysEarly;
private String promotionCode;
private static final String emptyString = "";
private static int ticketID; // Generates ticket number
public Ticket (double price, int daysEarly) { // Constructs ticket with given price, # of days early, no promo, assigns ticket #
this.price = price;
this.daysEarly = daysEarly;
ticketID += 1;
if (ticketID < 0) {
throw new EmptyStackException();
}
}
public int getDaysEarly(){
return daysEarly;
}
public double getPrice() {
return price;
}
public String getPromotionCode(){
if (promotionCode == null) return emptyString;
if (promotionCode.equals("KEXP call-in winner")) promotionCode = ("KEXP call in winner (student)");
return promotionCode;
}
public String setPromotionCode(String code){
if (code == null) throw new Error();
this.promotionCode = code;
return promotionCode;
}
public String toString(){
return "Ticket ID: " + ticketID + ", Price: $" + getPrice() + ", Days Early: " + getDaysEarly() + ", Promotion Code: " + getPromotionCode() + ".";
}
public static int getTicketCount(){
return ticketID;
}
public boolean equals(Ticket one) {
if (price == one.price && promotionCode.equals(one.promotionCode)) return true;
else return false;
}
}
As follows is the area where I'm trying to do math on super parameters...
I put "price/2" within param of sub to take care of math but I still need another "if statement" metaphorically
class StudentTicket extends Ticket {
private static final int daysEarly = 14;
public StudentTicket(double price, boolean honors) {
/*
Student tickets are always bought by campus ticket sales agency, two weeks in advance.
Students always get 50% off initial price.
Honor students get an addition $5 off after the 50%, down to a minimum of $0.
Student tickets have special promo codes.
*/
super(price/2, daysEarly);
// HOW DO I CALL UPON SUPER AFTER ALREADY HAVING DONE SO ???
// I STILL NEED TO SUBTRACT 5 BASED ON HONORS BOOLEAN OF SUBCLASS
// HOW DO I ADD AN IF STATEMENT INTO PARAM OF SUPER ???
// All you will do is make a call to super constructor and pass appropriate parameters
// So the idea is when I create a instance of StudentTicket and return price it should return me a discounted.
// That means you need to override the getPrice() method in superclass to update the ticket price
}
}
I was told to override the getPrice method but I don't know of any way to access the sub parameters
You could create a setPrice() method in the ticket class:
...
public int getDaysEarly(){
return daysEarly;
}
public void setPrice(double newPrice){
price = newPrice;
}
public double getPrice() {
return price;
}
...
Then do this in the StudentTicket constructor:
public StudentTicket(double price, int daysEarly, boolean honors) {
super(price/2, daysEarly);
if(honors == true)
setPrice(getPrice() - 5);
}
Because your methods are type: public and StudentTicket is a child of Ticket class, it should be able to access and utilize any public or protected methods from its parent.
Or you could do as haoyu wang mentioned, and declare price as protected.
I'm very new to Java and I keep getting this error and I can't figure it out.
Error: Could not find or load main class
restaurantclient.RestaurantClient
Java Result: 1
This is on Netbeans and I'm sure I've done everything right. This is for my homework for a Java class and I would really appreciate your help. I have been working on this problem for days now.
import java.text.DecimalFormat;
public class RestaurantClient {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Restaurant r1;
Restaurant r2;
r1 = new Restaurant("PizzaHut", 152, (float) 4.95); //instantiating
r2 = new Restaurant("Dominos", 10, (float) 3.657);
System.out.print(r1.toString());
System.out.print(r2.toString());
r2.setPeopleServed(r1.getPeopleServed());
r2.setAveragePrice(r1.getAverageMeal());
if (r1.equals(r2)) //checking if equal
System.out.println("\nThe two objects are the same");
else
System.out.println("\nThe two objects are NOT the same");
r2.setName(r1.getName());
if (r1.equals(r2)) //checking if equal
System.out.println("\nThe two objects are the same");
else
System.out.println("\nThe two objects are NOT the same");
DecimalFormat pricePattern = new DecimalFormat("$###,###,000.00");
System.out.println("Tax paid per year: " + pricePattern.format(r1.averageTaxes()));
}
}
//Restaurant.java
public class Restaurant extends Store {
private int peopleServed;
private float avgmeal;
public Restaurant(String newName, int peopleServed, float avgmeal) {
super(newName);
setPeopleServed(peopleServed);
setAveragePrice(avgmeal);
}
public void setPeopleServed(int newpeopleServed) {
if (newpeopleServed >= 0)
peopleServed = newpeopleServed; //mutator alows client to change the value of name
else
System.out.println("Number has to be greater than zero");
}
public void setAveragePrice(float newprice) {
if (newprice >= 0)
avgmeal = newprice; //mutator alows client to change the value of name
else
System.out.println("Number has to be greater than zero");
}
public int getPeopleServed() {
return peopleServed; //accessor; returns current value
}
public float getAverageMeal() {
return avgmeal; //accessor; returns current value
}
public String toString() {
return "Name of store is: " + super.getName() +
"\nNumber of people served is " + peopleServed +
"\nAverage price per person is " + avgmeal + "\n";
}
public boolean equals(Object o) {
if (!(o instanceof Restaurant))
return false;
else {
Restaurant objRest = (Restaurant) o;
if (avgmeal == objRest.avgmeal && peopleServed == objRest.peopleServed && super.equals(objRest))
return true;
else
return false;
}
}
public double averageTaxes() {
double avgtaxes = (double)(super.taxrate * (peopleServed * avgmeal * 365));
return avgtaxes; //accessor; returns current value
}
}
//Store.java
public class Store {
private String storename;
public final float taxrate = (float) .08000;
public Store(String newName) //constructor
{
setName(newName);
}
public String getName() {
return storename; //accessor; returns current value
}
public void setName(String newName) {
storename = newName; //mutator alows client to change the value of name
}
public String toString() {
return "Name of store is: " + storename;
}
public boolean equals(Object o) {
if (!(o instanceof Store))
return false;
else {
Store objStore = (Store) o;
if (storename.equals(objStore.storename))
return true;
else
return false;
}
}
}
The system is looking for a main class restaurantclient.RestaurantClient, so a class RestaurantClient in package restaurantClient, but your class RestaurantClient seems to be in the default package.
try this if you are not getting any compilation issues.
You can :
RightClick on project node and go to Set configuration.
Select the main class for your application.
Then clean and build.
Even if the above steps don't work for you then then delete the Netbeans cache by deleting the (index) folder
Fore more details
Follow the stackOverflow question
Netbeans - Error: Could not find or load main class
I have the following code which contains a run-time error. The code was meant to print out:
Vehicle mode:flight Fuel:propane Max Altitude:10000
Vehicle mode:traversal Fuel:coal Horsepower:5000
I could not find it myself (as I am fairly new to coding) and would like some help if possible.
Thanks.
class Main {
public static void main(String[] args) {
HotAirBalloon airbag = new HotAirBalloon(10000);
Locomotive loco = new Locomotive(5000);
System.out.println(airbag.toString());
System.out.println(loco.toString());
}
}
class Vehicle {
String mode, fuel;
public String toString() {
return "Vehicle Mode:" + mode + " Fuel:" + fuel;
}
}
class HotAirBalloon extends Vehicle {
int maxAltitude;
HotAirBalloon(int _alt) {
mode = "flight";
fuel = "propane";
maxAltitude = _alt;
}
public String toString() {
return toString() + " Max Altitude:" + maxAltitude;
}
}
class Locomotive extends Vehicle {
int horsePower;
Locomotive(int _hp) {
mode = "traversal";
fuel = "coal";
horsePower = _hp;
}
public String toString() {
return toString() + " Horsepower:" + horsePower;
}
}
Because you are trying to call the super classes version of the current method you need to add super.toString()
//old
return toString() + " Horsepower:" + horsePower;
//new
return super.toString() + " Horsepower:" + horsePower;
You also need to do this with your other subclass
When you a method calls itself its called recursion, where a method keeps calling itself until a certain condition.
This code will do fine. the problem was that you were calling toString() multiple times which was causing a Stack overflow. plus you have to declare a String in parent class vehicle and update it in the child classes with flight mode etc..run the code below:
class Main {
public static void main(String[] args) {
HotAirBalloon airbag = new HotAirBalloon(10000);
Locomotive loco = new Locomotive(5000);
System.out.println(airbag.toString());
System.out.println(loco.toString());
}
}
class Vehicle {
String mode, fuel;
String s;
}
class HotAirBalloon extends Vehicle {
int maxAltitude;
HotAirBalloon(int _alt) {
mode = "flight";
fuel = "propane";
maxAltitude = _alt;
s= "Vehicle Mode:" + mode + " Fuel:" + fuel;
}
public String toString() {
return s + " Max Altitude:" + maxAltitude;
}}
class Locomotive extends Vehicle {
int horsePower;
Locomotive(int _hp) {
mode = "traversal";
fuel = "coal";
horsePower = _hp;
s= "Vehicle Mode:" + mode + " Fuel:" + fuel;
}
public String toString() {
return s+ " Horsepower:" + horsePower;
}
}
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 8 years ago.
Improve this question
Why is it when I call System.out.println(classroom.toStringLong()) I get: classroom: a large lecture hall with a null that goes null to null?
The correct output is supposed to be: classroom: a large lecture hall with a door that goes outside to sidewalk
public class Main {
public static void main(String[] args) {
Space classroom = new Space();
classroom.setName("classroom");
classroom.setDescription("a large lecture hall");
Space sidewalk = new Space();
sidewalk.setName("sidewalk");
sidewalk.setDescription("a plain concrete sidewalk with weeds growing through the cracks");
Portal door = new Portal();
door.setName("door");
door.setDirection("outside");
door.setDestination(sidewalk);
classroom.setPortal(door);
System.out.println(classroom.toStringLong());
}
}
public class Space {
private String _name;
private String _description;
private Portal _portal;
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String getName() {
return _name;
}
public void setName(String _name){
this._name=_name;
}
public String getDescription() {
return _description;
}
public void setDescription(String _description){
this._description=_description;
}
public Portal getPortal() {
return _portal;
}
public void setPortal(Portal _portal){
this._portal=_portal;
}
public String toString(){
return _name;
}
public String toStringLong(){
if (_portal!= null){
Portal p= new Portal();
p.toStringLong();
String Longcombined=_name + ": " + _description+" with a "+p.toStringLong();
return Longcombined;
}
else{
String Long=_name + ": " + _description;
return Long;
}
}
}
public class Portal {
private String _name;
private String _direction;
private Space _destination;
public String getName() {
return _name;
}
public void setName(String _name){
this._name=_name;
}
public String getDirection(){
return _direction;
}
public void setDirection(String _direction){
this._direction=_direction;
}
public Space getDestination(){
return _destination;
}
public void setDestination(Space _destination){
this._destination=_destination;
}
public String toString(){
String combined=_name+ " that goes "+_direction;
return combined;
}
public String toStringLong(){
Space space=new Space();
String combined=toString() + " to " + space.getDescription() ;
return combined;
}
}
You are creating a new object of space and printing its description which is null
rewrite your toStringLong() method to
In class Space
public String toStringLong(){
if (_portal!= null)
{
// comment this Portal p= new Portal();
_portal.toStringLong();
String Longcombined=_name + ": " + _description+" with a "+_portal.toStringLong();
return Longcombined;
}
else
{
String Long=_name + ": " + _description;
return Long;
}
}
Class Portal ->
public String toStringLong()
{
String combined=toString() + " to " + _destination.getDescription() ;
return combined;
}
Hope this will solve your problem.
When run the this code "Space space=new Space();" inside of the toStringLogn() method, new space object is created and also all instant variables of this object are initialized with their default values. Default value of the String is "null". That is why you get null value when you use this object.
It is better to redefine your toStringLong() as follows,
String combined=toString() + " to " + _destination.getDescription() ;
return combined;