• 0

Help with Assignment - Java - Student Class


Question

import java.awt.Point;
import java.util.ArrayList;
import java.util.Scanner;

public class Cannonball {

public static void main(String[] args) {
    //Part 1: Open Scanner
    Scanner keyboard = new Scanner(System.in);

    //Part 2: Create a new cannonball
    Ball bowling = new Ball(0);

    //Part 3: Ask user for initial angle and starting velocity
    System.out.println("Alright, give us the angle at which to fire: ");
    bowling.setAngle(keyboard.nextDouble());
    System.out.println("And what is the initial velocity: ");
    bowling.setVel(keyboard.nextDouble());

    //Part 4: Return the points of the cannonball's flight
    for(int i=0; i<bowling.shoot.size(); i++) System.out.println(bowling.shoot);

    //Part x: Close input
    keyboard.close();
}

}

class Ball{
private double xPos, yPos, deltaSec;
private double alpha, v;
private double yVel, xVel;
private static final double gravity = -9.81;

public Ball(double xPos){
    this.xPos=xPos;
    yPos=0;
}

public Point move(double deltaSec){
    xPos += xVel*deltaSec;
    yPos += yPos*deltaSec;
    return new Point();
}

public void yVel(){
    yVel=v*Math.sin(alpha)*(deltaSec*gravity);
}

public void xVel(){
    xVel=v*Math.cos(alpha);
}

public Point getLocation(double xPos, double yPos){
   return new Point((int)xPos, (int)yPos); //Point only takes int coordinates
}



public void setAngle(double aplha){
    this.alpha=alpha;
}

public void setVel(double v){
    this.v=v;
}

public ArrayList<Point> shoot = new ArrayList<Point>();
{
    while(deltaSec<60){
        move(deltaSec);
        shoot.add(getLocation(xPos, yPos));
        deltaSec++;
    }
}
}

What I am trying to accomplish here is to output an array of X and Y coordinates as the cannonball is in flight. However, when I run the program, I get a bunch of Point[x=0,y=0] within the array.

attach is the assignment instruction can somebody help

CannonBall-Instructions-JavaDocAbstract.pdfFetching info...

8 answers to this question

Recommended Posts

  • 0
  On 03/12/2014 at 00:26, atyemail said:

 

I am using jGRASP to code this

1
 

 

 

When i coded in Java i used Eclipse; does jGRASP have debug? if yes then it's a great tool for seeing the flow of the logic and code.

  • 0

Just from looking at your code, the shoot subroutine looks odd. I'm assuming you're trying to fill an array of points, then return it somehow. That can be done in two ways. Either define a class scope variable and a 'get' routine, or define and return it directly in 'shoot':

public ArrayList<Point> shoot ( double launchAngle, double initialVelocity ) {
	
	ArrayList<Point> trajectory = new ArrayList<Point>();
	deltasec = 0;
	
	setAngle ( launchAngle );
	setVelocity ( initialVelocity );
	
	while ( deltaSec < 60 ) {
		move ( deltaSec );
		trajectory.add ( getLocation () );
		deltaSec++;
	}
	
	return trajectory;
}
Although your assignment doesn't seem to want you to do it this way. From a cursory glance, it seems to want you to print a line of information and graphic in shoot after every tick (1/10 of a second), not store each movement in an array.

Edit: A small tip. Don't access a class' member variables directly. That breaks rules of encapsulation and creates a dependency on the internal structure of the Ball class.

  • 0

This is fairly straightforward by deduction. xPos and yPos have a default value of 0. The only place where they are set a different value is in move() with this line:

xPos += xVel*deltaSec;
yPos += yVel*deltaSec;

The result of xVel * deltaSec is 0 if either operand is 0. We can see that deltaSec will not be 0 after the first iteration of your while loop, so it must be xVel and yVel that remain at 0 throughout. So now we need to figure out why xVel and yVel remain at 0.

 

The only place where you set xVel and yVel are in the xVel() and yVel() methods:

public void yVel(){
    yVel=v*Math.sin(alpha)*(deltaSec*gravity);
}


public void xVel(){
    xVel=v*Math.cos(alpha);
}

Are these methods called anywhere? No! Hence xVel and yVel remain at 0, hence xPos and yPos remain at 0.

 

This is very weird design and you got bitten by it. Instead of adding calls to xVel() and yVel(), just have setVel() do it:

public void setVel(double v){
    this.v=v;
    yVel=v*Math.sin(alpha)*(deltaSec*gravity);
    xVel=v*Math.cos(alpha);
}

after all, why would you ever want to set the velocity without also setting its x and y components? It creates that weird incoherent state where the x and y components do not match the velocity of the ball.

So now you can remove the pointless xVel() and yVel() methods. Or perhaps these were intended to be property getters and you meant to write:

public double yVel(){
    return yVel;
}

public double xVel(){
    return xVel;
}
  • 0
  On 03/12/2014 at 02:22, atyemail said:

it still does not work

1

There are a few problems with your code.

1) As Andre noted, you're not calling the relevant function(s) to calculate the vector velocity. Additionally, Java's Math.sin / cos functions accept radians, not degrees. The conversion function Math.toRadians should fix that.

2) You're not accounting for gravitational acceleration in your move routine.

3) According to the assignment, your shoot implementation should call the move subroutine for each tick (currently defined as 100 miliseconds). Your code appears to be arbitrarily counting to 60.

In truth though, that assignment is quite vague and ambiguous. I had trouble understanding the intent of some of it. The use of private static functions in the Cannonball class for example is puzzling to say the least. Here's how I'd implement it:

 

[snipped - please don't give full solutions to homework assignments - Andre S.]

  • 0

Interestingly, precomputed quantities don't quite match stepped quantities. Probably a flaw in my trigonometric/kinematic math.

	private void setInitialVelocity ( double theta, double v0 ) {
		
		double sin = Math.sin ( Math.toRadians ( theta ) );
		
		/* v0x = v0 COS ? */
		/* cosine gives us the ratio of the adjacent (horizontal) to the hypotenuse. sohCAHtoa. v0x per second */
		xVel = v0 * Math.cos ( Math.toRadians ( theta ) );

		/* v0y = v0 SIN ?  */
		/* sine gives us the ratio of the opposite (vertical) to the hypotenuse. SOHcahtoa. v0y per second */
		yVel = v0 * sin;

		range 		= ( v0 * v0 ) / GRAVITY_METERSperSECONDsquared * Math.sin ( Math.toRadians ( 2 * theta ) );
		timeToMaxHeight = v0 * sin / GRAVITY_METERSperSECONDsquared;
		timeOfFlight 	= 2 * v0 * sin / GRAVITY_METERSperSECONDsquared;
	}
$  java ProjectileMotion
Enter a starting angle, 1-89 degrees: 45
Enter a firing velocity (0-20 meters/second): 20
range:40.77, tmax: 1.44, tflight: 2.88
sec: 0.10, x: 1.41, y: 1.41     |  *
sec: 0.20, x: 2.83, y: 2.73     |   *
sec: 0.30, x: 4.24, y: 3.95     |    *
sec: 0.40, x: 5.66, y: 5.07     |      *
sec: 0.50, x: 7.07, y: 6.09     |       *
sec: 0.60, x: 8.49, y: 7.01     |        *
sec: 0.70, x: 9.90, y: 7.84     |        *
sec: 0.80, x:11.31, y: 8.57     |         *
sec: 0.90, x:12.73, y: 9.20     |          *
sec: 1.00, x:14.14, y: 9.73     |          *
sec: 1.10, x:15.56, y:10.16     |           *
sec: 1.20, x:16.97, y:10.50     |           *
sec: 1.30, x:18.38, y:10.73     |           *
sec: 1.40, x:19.80, y:10.87     |           *
sec: 1.50, x:21.21, y:10.91     |           *
sec: 1.60, x:22.63, y:10.86     |           *
sec: 1.70, x:24.04, y:10.70     |           *
sec: 1.80, x:25.46, y:10.45     |           *
sec: 1.90, x:26.87, y:10.09     |           *
sec: 2.00, x:28.28, y: 9.65     |          *
sec: 2.10, x:29.70, y: 9.10     |          *
sec: 2.20, x:31.11, y: 8.45     |         *
sec: 2.30, x:32.53, y: 7.71     |        *
sec: 2.40, x:33.94, y: 6.87     |       *
sec: 2.50, x:35.36, y: 5.93     |      *
sec: 2.60, x:36.77, y: 4.89     |     *
sec: 2.70, x:38.18, y: 3.75     |    *
sec: 2.80, x:39.60, y: 2.52     |   *
sec: 2.90, x:41.01, y: 1.18     |  *
sec: 3.00, x:42.43, y:-0.25     | *
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • You cannot disable or fully delete Safari on either iOS or macOS. You can ignore it, just like you can with Edge, if that's what you want to do.
    • UniGetUI 3.3.1 by Razvan Serea UniGetUI is an application whose main goal is to create an intuitive GUI for the most common CLI package managers for Windows 10 and Windows 11, such as Winget, Scoop and Chocolatey. With UniGetUI, you'll be able to download, install, update and uninstall any software that's published on the supported package managers — and so much more. UniGetUI features Install, update and remove software from your system easily at one click: UniGetUI combines the packages from the most used package managers for windows: WinGet, Chocolatey, Scoop, Pip, Npm and .NET Tool. Discover new packages and filter them to easily find the package you want. View detailed metadata about any package before installing it. Get the direct download URL or the name of the publisher, as well as the size of the download. Easily bulk-install, update or uninstall multiple packages at once selecting multiple packages before performing an operation Automatically update packages, or be notified when updates become available. Skip versions or completely ignore updates in a per-package basis. Manage your available updates at the touch of a button from the Widgets pane or from Dev Home pane with UniGetUI Widgets. The system tray icon will also show the available updates and installed package, to efficiently update a program or remove a package from your system. Easily customize how and where packages are installed. Select different installation options and switches for each package. Install an older version or force to install a 32bit architecture. [But don't worry, those options will be saved for future updates for this package] Share packages with your friends to show them off that program you found. Here is an example: Hey @friend, Check out this program! Export custom lists of packages to then import them to another machine and install those packages with previously-specified, custom installation parameters. Setting up machines or configuring a specific software setup has never been easier. Backup your packages to a local file to easily recover your setup in a matter of seconds when migrating to a new machine UniGetUI 3.3.1 changelog: Adress executable corruption/integrity detection and semi-automatic resolution: UniGetUI will check for corruption issues. If found, the user will be prompted to repair them. The crash report will contain an integrity report In both cases, if UniGetUI detects an integrity violation and the UniGetUI installer is placed on the installation directory (which will be by default since this release), UniGetUI will ask the user to confirm to start an automated reinstall process. UniGetUI can be reinstalled from Windows Apps and Features -> UniGetUI -> Modify. This will force a reinstall Fixed crashes and issues with GitHub cloud backup and GitHub login Fixed an issue where certain in-app popups wouldn't show the acrylic background properly Migrated to AppSdk Titlebar, and removed WinUIEx as a dependency Improvements to UniGetUI Elevator Fix a few UI crashes and deadlocks involving loading dialogs Reverted a Toolbar UI change that combined different options into a menu. Now the main action has its own button again Other fixes and improvements What's Changed Update icons and screenshots from the excel file by @github-actions[bot] in #3884 Load translations from Tolgee by @martinet101 in #3937 Download: UniGetUI 3.3.1 | 53.3 MB (Open Source) Links: WingetUI Home Page | GitHub | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • You have reported this issue at least once into their feedback hub?
    • You can disable Chrome on Android and forget that it even exists, you can do the same for Safari in Apple's operating systems. Only ChromeOS is tied with Chrome because the whole OS is Chrome. Safari doesn't have dominant market share but Apple allows you to disable Safari. So why exactly we can't have the same with Edge and only EU Windows users can uninstall Edge? There isn't any valid reason having Edge, the browser, needed for any other app, for widgets etc. That is what Edge webview2 is for.
    • China throws a wrench into Nvidia's H20 comeback plan by Paul Hill China’s Cyberspace Administration (CAC) has summoned Nvidia over alleged security vulnerabilities in its H20 chips. The CAC said that the chips have serious security issues with specific concerns over tracking and positioning and remote shutdown technologies. This development poses a big hurdle for Nvidia just as H20 sales were set to resume after the US reversed a ban that was first imposed in April. According to CNBC, Nvidia had already taken a $4.5 billion writedown on the unsold H20 inventory in May and said sales in its last financial quarter would have been $2.5 billion if export curbs could have been avoided. The CAC is concerned about the chips because of calls from US lawmakers for mandatory tracking features on advanced chip exports. For example, the proposed US Chip Security Act from Senator Tom Cotton and others would require location reporting and remote modification capabilities. If these backdoors have already been baked in, or get added in the future, China would view them as a threat to national security and data privacy. US lawmakers argue that these tracking capabilities are needed to prevent chip smuggling to ensure compliance with export controls which also apply to China. Given its actions, the CAC has reason to believe that the tracking technology is already present. Nvidia CEO Jensen Huang recently visited the Chinese capital, Beijing, to signal the company’s commitment to the Chinese market and announced the resumption of sales of the H20. It is believed that Nvidia placed new orders for 300,000 H20 chipsets with TSMC to meet the anticipated demand. Given the CAC’s decision, it could mess up Nvidia’s plans and force it to consider new ways to navigate US export policies and retain its lucrative China market share. The US is keen to hamper China's AI efforts so that it maintains a lead in the AI race. By limiting access to powerful hardware, it forces China to make more efficient models, or develop powerful hardware itself, slowing down its progress.
  • Recent Achievements

    • Dedicated
      f2030 earned a badge
      Dedicated
    • Week One Done
      whiloh earned a badge
      Week One Done
    • Week One Done
      memnoch earned a badge
      Week One Done
    • First Post
      UAVXP earned a badge
      First Post
    • Dedicated
      Xinotema earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      664
    2. 2
      ATLien_0
      207
    3. 3
      Xenon
      133
    4. 4
      neufuse
      124
    5. 5
      Michael Scrip
      122
  • Tell a friend

    Love Neowin? Tell a friend!