Question

**JAVA** Hi! Can't figure this out, but if you could give it a shot, I'd appreciate...

**JAVA** Hi! Can't figure this out, but if you could give it a shot, I'd appreciate it! Everything is explained in the program via comments, and I just need help implementing the methods. Instructions for the methods are commented on top of said method. It's supposedly straightforward. Methods that need to be solved are in bold. Some might already be implemented. Just based off what's in this class, is supposed to lead to the outcome. This is all the info that I got for the assignment and everything- the outcome, instructions, etc is in the comments within the program. Even if you only implement one or two methods, honestly anything helps. :)

package mobiles;

import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Line2D;

/**
* A Mobile is either a Bob or Rod.
*
* A Bob is a Mobile consists of a weight hanging from a vertical wire.
*
* Here's a diagram, where W denotes a weight:
*
* <pre>
* |
* W
* </pre>
*
* A Rod is a Mobile that consists of a horizontal rod that has one Mobile hanging from its left end and another Mobile
* hanging from its right end. The rod is hanging from a vertical wire. The distance along the rod from the vertical
* wire to the left end is called the left length, and the distance from the vertical wire to the right end is called
* the right length.
*
* Here's a diagram:
*
* <pre>
* _____|__________
* | |
* L R
* </pre>
*
* The left length is 5 and the right length is 10. L and R are the left and right Mobiles, respectively.
*/
public class Mobile
{
/**
* True if the Mobile is a Bob; false if the Mobile is a Rod.
*/

private boolean isBob;

/**
* If isBob is true, contains the weight of the Bob.
*/

private int weight;

/**
* If isBob is false, contains the left length of the Rod.
*/

private int leftLength;
  
/**
* If isBob is false, contains the right length of the Rod.
*/

private int rightLength;
  
/**
* If isBob is false, contains the left Mobile of the Rod.
*/

private Mobile left;
  
/**
* If isBob is false, contains the right Mobile of the Rod.
*/

private Mobile right;

/**
* Creates a Bob with the given weight.
*/

public Mobile (int weight)
{
this.isBob = true;
this.weight = weight;
}

/**
* Creates a Rod of the given configuration.
*/

public Mobile (int leftLength, int rightLength, Mobile left, Mobile right)
{
this.isBob = false;
this.leftLength = leftLength;
this.left = left;
this.rightLength = rightLength;
this.right = right;
}

// Formatting constants
public final static double WIRE = 100;
public final static double UNIT = 10;
public final static double GAP = 2;
public final static double TOP = 10;
public final static int WIDTH = 1200;
public final static int HEIGHT = 800;

/**
* Draws this Mobile on g, beginning at point (x,y).
*/
public void display (Graphics2D g, double x, double y)
{
if (isBob)
{
FontMetrics fm = g.getFontMetrics();
int weightWidth = fm.stringWidth(weight + "");
int height = fm.getHeight();
g.draw(new Line2D.Double(x, y, x, y + WIRE));
g.draw(new Arc2D.Double(x - height, y + WIRE, 2 * height, 2 * height, 0, 360, Arc2D.OPEN));
g.drawString(weight + "", (float) (x - weightWidth / 2), (float) (y + WIRE + 1.25 * height));
}

else
{
// Get the widths of the labels
FontMetrics fm = g.getFontMetrics();
int leftLabelWidth = fm.stringWidth(leftLength + "");
int rightLabelWidth = fm.stringWidth(rightLength + "");

// Show the mobile askew according to the degree of imbalance
double leftTorque = left.weight() * leftLength;
double rightTorque = right.weight() * rightLength;
double theta = (rightTorque - leftTorque) / 100 * Math.PI / 6;
theta = Math.min(theta, Math.PI / 6);
theta = Math.max(theta, -Math.PI / 6);

// Compute the endpoints of the rod
double leftX = x - Math.cos(theta) * (leftLength * UNIT);
double leftY = y + WIRE - Math.sin(theta) * (leftLength * UNIT);
double rightX = x + Math.cos(theta) * (rightLength * UNIT);
double rightY = y + WIRE + Math.sin(theta) * (rightLength * UNIT);

// Translate
AffineTransform at = new AffineTransform();
at.translate(x, y + WIRE);
g.setTransform(at);
  
// Draw the wire
g.draw(new Line2D.Double(0, 0, 0, -WIRE));
  
// Rotate
at.rotate(theta);
g.setTransform(at);

// Draw the rod and display the text
g.draw(new Line2D.Double(-leftLength * UNIT, 0, rightLength * UNIT, 0));
g.drawString(leftLength + "", (float) (-leftLength * UNIT / 2 - leftLabelWidth / 2), (float) -GAP);
g.drawString(rightLength + "", (float) (rightLength * UNIT / 2 - rightLabelWidth / 2), (float) -GAP);

// Cancel the rotation
at.setToRotation(0);
g.setTransform(at);

// Display the left and right Mobiles
left.display(g, leftX, leftY);
right.display(g, rightX, rightY);
}
}

/**
* Returns the total weight of all the Bobs in this Mobile.
*/

public int weight ()
{
  
return 0;
}

/**
* Reports whether all the Rods in this Mobile are completely horizontal. A Rod will be horizontal if the product of
* its left length and the weight of its left Mobile equals the product of its right length and the weight of its
* right Mobile.
*/

public boolean isBalanced ()
{
return false;
}

/**
* Returns the length of the longest path through this Mobile. There is one path for every Bob in the Mobile. Each
* path leads from the top of the Mobile to a Bob, and its length is the number of Rods encountered along the way
* plus one.
*/

public int depth ()
{
return 0;
}

/**
* Returns the number of Bobs contained in this Mobile.
*/

public int bobCount ()
{
return 0;
}

/**
* Returns the number of Rods contained in this Mobile.
*/

public int rodCount ()
{
return 0;
}

/**
* Returns the length of the longest Rod contained in this Mobile. If there are no Rods, returns zero.
*/

public int longestRod ()
{
return 0;
}

/**
* Returns the weight of the heaviest Bob contained in this Mobile.
*/

public int heaviestBob ()
{
return 0;
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Source code: Implementation of 3 methods : weight(), bobCount() and rodCount()

// getter methods for private instance varibales isBob, weight, left, right
public boolean getIsBob()
{
return this.isBob;
}

public int getWeight()
{
return this.weight;
}

public Mobile getRight()
{
return this.right;
}
public Mobile getLeft()
{
return this.left;
}

// Returns the total weight of all the Bobs in this Mobile.
public int weight()
{
// this will store total weight of all the Bobs in this Mobile
int totalWeight=0;

// Create an empty stack that will be used to traverse this Mobile analogous to the iterative traversal of binary tree
Stack<Mobile> stack = new Stack<Mobile>();

// Pushing this Mobile as first element in the stack
stack.push(this);

// iterating this Mobile
do {
// removing the top Mobile element from the stack
Mobile m = stack.pop();

// check if the current Mobile is Bob or Rod
if(m.getIsBob()) // if Bob then add its weight to the variable totalWeight
totalWeight += m.getWeight();
else // if Rod then push the right and left Mobiles of the Rod on the stack
{
stack.push(m.getRight());
stack.push(m.getLeft());
}
} while(!stack.empty()); // stop the loop when the stack becomes empty

return totalWeight;
}

// Returns the number of Bobs contained in this Mobile.
public int bobCount()
{
// this will store the number of Bobs contained in this Mobile
int count=0;

// Create an empty stack that will be used to traverse this Mobile analogous to the iterative traversal of binary tree
Stack<Mobile> stack = new Stack<Mobile>();

// Pushing this Mobile as first element in the stack
stack.push(this);

// iterating this Mobile
do {
// removing the top Mobile element from the stack
Mobile m = stack.pop();

// check if the current Mobile is Bob or Rod
if(m.getIsBob()) // if Bob then increment the count varibale
count++;
else // if Rod then push the right and left Mobiles of the Rod on the stack
{
stack.push(m.getRight());
stack.push(m.getLeft());
}
} while(!stack.empty()); // stop the loop when the stack becomes empty

return count;
}

// Returns the number of Rods contained in this Mobile.
public int rodCount()
{
// this will store the number of Rods contained in this Mobile
int count=0;
Stack<Mobile> stack = new Stack<Mobile>();
stack.push(this);

do {
Mobile m = stack.pop();

// check if the current Mobile is Bob or Rod
if(!m.getIsBob()) // if Rod then increment the count variable and also push the right and left Mobiles of the Rod on the stack
{
count++;
stack.push(m.getRight());
stack.push(m.getLeft());
}
} while(!stack.empty());

return count;
}

Note: Also import following packages:

import java.io.*;

import java.util.*;

Please refer to below screenshots to understand the indentation of source code:

Add a comment
Know the answer?
Add Answer to:
**JAVA** Hi! Can't figure this out, but if you could give it a shot, I'd appreciate...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This is a Clock program in Java. Can you fix my Java program error, and add function to display c...

    This is a Clock program in Java. Can you fix my Java program error, and add function to display current time currently? import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.util.Date; import javax.swing.JPanel; import javax.swing.WindowConstants; public class Clock extends javax.swing.JFrame {    public int hour;    public int min;    public int sec;    ClockDial cd;    public Clock() {        setSize(510, 530);        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);        cd = new ClockDial(this);        getContentPane().add(cd);        Date curr = new Date();        String time = curr.toString();        hour = Integer.parseInt(time.substring(11, 13));        min = Integer.parseInt(time.substring(14, 16));        sec...

  • Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import...

    Java BlackJack Game: Help with 1-4 using the provided code below Source code for Project3.java: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class Project3 extends JFrame implements ActionListener { private static int winxpos = 0, winypos = 0; // place window here private JButton exitButton, hitButton, stayButton, dealButton, newGameButton; private CardList theDeck = null; private JPanel northPanel; private MyPanel centerPanel; private static JFrame myFrame = null; private CardList playerHand = new CardList(0); private CardList dealerHand = new CardList(0);...

  • Java Help, Will definitely give a thumbs up if it works. Declare a class ComboLock that...

    Java Help, Will definitely give a thumbs up if it works. Declare a class ComboLock that works like the combination lock in a gym locker (Consult the API provided to look for the methods needed). The locker is constructed with a combination - three numbers between 0 and 39. The reset method resets the dial so that it points to 0. The turnLeft and turnRight methods turn the dial by a given number of ticks to the left or right....

  • Java Program The goal of this assignment is to develop an event-based game. You are going...

    Java Program The goal of this assignment is to develop an event-based game. You are going to develop a Pong Game. The game board is a rectangle with a ball bouncing around. On the right wall, you will have a rectangular paddle (1/3 of the wall height). The paddle moves with up and down arrows. Next to the game board, there will be a score board. It will show the count of goals, and count of hits to the paddle....

  • CONVERT THIS JAVA CODE WITH THE JAVA DOC GUIDELINES WHERE APPROPRIATE. DO NOT CHANGE THE CODE....

    CONVERT THIS JAVA CODE WITH THE JAVA DOC GUIDELINES WHERE APPROPRIATE. DO NOT CHANGE THE CODE. SAME CODE SHOULD BE USED FOR THE DOCUMENTATION PURPOSES. ONLY INSERT THE JAVA DOC. //Vehicle.java public class Vehicle {    private String manufacturer;    private int seat;    private String drivetrain;    private float enginesize;    private float weight; //create getters for the attributes    public String getmanufacturer() {        return manufacturer;    }    public String getdrivetrain() {        return drivetrain;...

  • Fix the todo in ball.java Ball.java package hw3; import java.awt.Color; import java.awt.Point; import edu.princeton.cs.algs4.StdDraw; /** *...

    Fix the todo in ball.java Ball.java package hw3; import java.awt.Color; import java.awt.Point; import edu.princeton.cs.algs4.StdDraw; /** * A class that models a bounding ball */ public class Ball {    // Minimum and maximum x and y values for the screen    private static double minX;    private static double minY;    private static double maxX;    private static double maxY;    private Point center;    private double radius;    // Every time the ball moves, its x position changes by...

  • *JAVA* Can somebody take a look at my current challenge? I need to throw a different...

    *JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> {    private int top, size;    private E arrS[];    private static final int MAX_STACK_SIZE = 10;    public ArrayStack() {        this.arrS = (E[]) new Object[MAX_STACK_SIZE];        this.top = size;        this.size = 0;...

  • How to build Java test class? I am supposed to create both a recipe class, and...

    How to build Java test class? I am supposed to create both a recipe class, and then a class tester to test the recipe class. Below is what I have for the recipe class, but I have no idea what/or how I am supposed to go about creating the test class. Am I supposed to somehow call the recipe class within the test class? if so, how? Thanks in advance! This is my recipe class: package steppingstone5_recipe; /** * *...

  • JAVA QUESTION: *******THE QUESTION:******** /** numberOfNodesAtDepth    *    * Returns the number of nodes with...

    JAVA QUESTION: *******THE QUESTION:******** /** numberOfNodesAtDepth    *    * Returns the number of nodes with depth == d    * Precondition: none    *    * param: d the depth to search for    *    * hint: use a recursive helper function    *        * ToDo 4    */    public int numNodesAtDepth(int d) {        return -1;    } **********USEFUL CODE FROM THE ASSIGNMENT:*********** public class simpleBST<Key extends Comparable<Key>, Value> {    private Node root;            ...

  • Hi! I'm working on building a GUI that makes cars race across the screen. So far...

    Hi! I'm working on building a GUI that makes cars race across the screen. So far my code produces three cars, and they each show up without error, but do not move across the screen. Can someone point me in the right direction? Thank you! CarComponent.java package p5; import java.awt.*; import java.util.*; import javax.swing.*; @SuppressWarnings("serial") public class CarComponent extends JComponent { private ArrayList<Car> cars; public CarComponent() { cars = new ArrayList<Car>(); } public void add(Car car) { cars.add(car); } public...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT