I'm programming a program that add feet and inch together(assume feet and inch are integer). I run into a compiler error. I know the problem is I'm missing the returning statement. But I don't know what to return.

public class Distance
{
	private int feet;
	private int inch;
	
	public Distance()
	{
	}
	
	public Distance(int ch, int ft)
	{
		feet = ft;
		inch = ch;
	}
	
	public int getFeet()
	{
	return feet;
	}
	
	public int getInch()
	{
	return inch;
	}
	
	public void setFeet(int f)
	{
	feet = f;
	}
	
	public void setInch(int c)
	{
		inch = c;
	}
	@Override
	public String toString()
	{
		return String.format("%d feet %d inch",getFeet(), getInch());
	}
	
	public Distance add(Distance d)
	{
		int i = getInch() + getInch();
		int f = getFeet() + getFeet();
		while (i>=12)
		{
			i = i-12;
			f++;
		}
		setFeet(f)
		setInch(i)
		
	}
	
	//public Distance subtract(Distance d)
	//{
		
	//}


	
}

This is my constructor class. The compiler error mark the add method because it is missing the return statement. I know I specify return type is Distance, but if I return Distance it still mark at compiler error. I probably can change Distance to void, but my teacher specify using "public Distance add(Distance d)". What should I return here?

This is the main method class.

public class DistanceTest
{
	public static void main(String[]args)
	{
		Distance d1 = new Distance(1, 5);
		Distance d2 = new Distance(1, 5)
		
		
		Distance d3 = d1.add(d2);
		
	}
}

Recommended Answers

All 3 Replies

if I return Distance it still mark at compiler error.

You forgot to post the error message.
Also you need to show the code that causes the error.

What should I return here?

The method says it returns a Distance object.
Do you want to return the current object (this)
or create a new object?

Also line 50 and 51 are missing the semicolon

Member Avatar for hfx642

Well...
On line 41, you've defined a method "add" with an input parameter "d" of type "Distance",
and you said that your method would return a result of type "Distance",
yet... your "add" method has no "return" statement.
Not to mention that your method "substract" is about to do the same thing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.