Points on an x, y graph can fall into one of 4 quadrants (or they can fall on on
ID: 3706755 • Letter: P
Question
Points on an x, y graph can fall into one of 4 quadrants (or they can fall on one of the axis). Quadrant 1 contains all points whose x and y values are both positive. Quadrant 2 contains all points with negative x but positive y. Quadrant 3 contains all points with negative x and y values. Quadrant 4 contains all points with positive x but negative y. If the point lies directly on the x and/or y axis, return 0.
- Write 1 non-static method called quadrant().
- The prototype for quadrant() is: public int quadrant();
There is a test main provided. Use this to run a couple simple tests on the code.
The output of running the test PointTest, if your code is working correctly, should be:
Point: (22, 31) is in Quadrant 1
Passed
Point: (33, -23) is in Quadrant 4
Passed
Point: (-14, 0) is in Quadrant 0
Passed
Explanation / Answer
class ModifiedPoint
{
private int x;
private int y;
public ModifiedPoint()
{
this(0,0);
}
public ModifiedPoint(int x,int y)
{
this.x = x;
this.y = y;
}
public void setX(int x)
{
this.x = x;
}
public int getX()
{
return x;
}
public void setY(int y)
{
this.y = y;
}
public int getY()
{
return y;
}
public int quadrant()
{
if( x>0 && y>0)
return 1;
else if(x<0 && y>0)
return 2;
else if(x<0 && y<0)
return 3;
else if(x>0 && y<0)
return 4;
else
return 0;
}
public String toString()
{
return "("+x+","+y+")";
}
}
class TestModifiedPoint
{
public static void main (String[] args)
{
System.out.println("Testing first quadrant");
ModifiedPoint p1 = new ModifiedPoint(22,31);
System.out.println(p1 +" is in quadrant "+p1.quadrant());
System.out.println();
System.out.println("Testing second quadrant");
ModifiedPoint p2 = new ModifiedPoint(33,-23);
System.out.println(p2 +" is in quadrant "+p2.quadrant());
System.out.println();
System.out.println("Testing third quadrant");
ModifiedPoint p3 = new ModifiedPoint(-14,0);
System.out.println(p3 +" is in quadrant "+p3.quadrant());
System.out.println();
}
}
Output:
Testing first quadrant
(22,31) is in quadrant 1
Testing second quadrant
(33,-23) is in quadrant 4
Testing third quadrant
(-14,0) is in quadrant 0
Do ask if any doubt. Please upvote.