Im currently trying to do an exercise for upcoming exam. But unfortunately he is already asleep and I have an exam tomorrow.
this is my code that I have done. Im not sure what to do with resetSpeed and I think there is also something wrong in trying to calculate timeToTravel method
package comp6700.mse;
/**
* COMP6700 Mid-Semester Exam, Question 3
*/
public class Q3Plane {
private String name;
private int speed;
private int distance;
private int time;
/**
* Constructor
*
* #param name The name of the plane
* #param speed The speed of the plane (in km/h),
*/
Q3Plane(String name, int speed) {
this.name = name;
this.speed = speed;
}
/** Return the speed of the plane */
int getSpeed() {
return this.speed;
}
/**
* Reset the speed of the plane according to the argument speed
* #param speed The new speed of the plane
*/
void resetSpeed(int speed) {this.speed = speed;}
/**
* Calculate the time to travel the specified distance at the current speed.
* #param distance The distance (in km)
* #return The time to travel the distance (in minutes)
*/
int timeToTravel(int distance) {
this.distance = distance;
this.time = time;
time = distance/speed;
return time ;
}
/**
* Return a string describing the plane and its speed,
* in the format
* "Plane NAME is travelling S km/h"
* where NAME is replaced by the plane's name, and S is replaced by
* the plane's speed.
*
* #return A string describing the plane and its speed
*/
#Override
public String toString() {
return ("Plane"+" "+name+" "+ "is travelling" +" " +speed+ " " + "km/h");
}
}
the error that i got is this
java.lang.AssertionError: Expected time of '42', but got '0'
updated: test case
public class Q3PlaneTest {
static final int DEFAULT_ITERATIONS = 10;
#Test
public void testGetSpeed() {
Random r = new Random();
for (int i = 0; i < DEFAULT_ITERATIONS; i++) {
String name = "NA"+r.nextInt(10000);
int speed = 600+r.nextInt(400);
Q3Plane p = new Q3Plane(name, speed);
int s = p.getSpeed();
assertTrue("Expected speed of '"+speed+"', but got '"+s+"'", s == speed );
}
}
#Test
public void testSetSpeed() {
Random r = new Random();
String name = "NA"+r.nextInt(10000);
int speed = 600+r.nextInt(400);
Q3Plane p = new Q3Plane(name, speed);
for (int i = 0; i < DEFAULT_ITERATIONS; i++) {
speed = 600+r.nextInt(400);
p.resetSpeed(speed);
int s = p.getSpeed();
assertTrue("Expected speed of '"+speed+"', but got '"+s+"'", s == speed );
}
}
#Test
public void testTimeToTravel() {
Random r = new Random();
String name = "NA"+r.nextInt(10000);
int s = 600+r.nextInt(400);
Q3Plane p = new Q3Plane(name, s);
for (int i = 0; i < DEFAULT_ITERATIONS; i++) {
s = 600+r.nextInt(400);
int d = 300+r.nextInt(500);
p.resetSpeed(s);
int t = p.timeToTravel(d);
int rt = (60 * d) / s;
assertTrue("Expected time of '"+rt+"', but got '"+t+"'", t == rt );
}
}
You are dividing long by an int and storing that value in an int type variable. Java will round down as you've told the JVM you want type int to hold time. You should use double instead.
Plane Class
public class Q3Plane {
private String name; // name of plane
private double speed; // km per hour
Q3Plane(String name, double speed) {
this.name = name;
this.speed = speed;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double timeToTravel(int distance) {
return ((distance/this.speed) * 60);
}
}
Unit Test
public class Q3PlaneTest {
#Test
public void testTimeToTravel() {
Q3Plane plane = new Q3Plane("TESTPLANE", 500);
double timeInMinutes = plane.timeToTravel(1000);
System.out.println(timeInMinutes);
assertTrue(timeInMinutes == 120d);
}
}
Update:
The unit test that was provided doesn't really make sense in real world. There is no guarantee that the division operation would not result in a non whole number. Using int makes no sense as in the real world you would not always being going whole number distance or speeds.
It turns out to be really simple
the answer is
time = (60*distance)/speed
Related
For my project I was wondering whether there is a way I can do this assignment without using serialization. Here are the guidelines to the project and the code I already have together:
The Canadian Forest Service wants to do a simple simulation of the growth and pruning of forests. Each forest has a name and exactly 10 trees. The trees are planted when they are 1' to 5' tall, and each tree has a individual growth rate of 50%-100% per year. For the simulation new trees are constructed randomly within these bounds. A forest is reaped (by lumberjacks) on demand - all trees above a specifed height are cut down and replaced with new trees.
The user interface to the simulation must allow the user to:
Display the current forest (with tree heights to 2 decimal places)
Discard the current forest and create a new forest
Simulate a year's growth in the current forest
Reap the current forest of trees over a user specified height, replacing the reaped trees with random new trees.
Save the information about the current forest to file (named after the forest)
Discard the current forest and load the information about a forest from a file.
Class1
import java.io.*;
import java.util.*;
public class Forest{
//constants
private static final int MAX_NUM_TREES = 10;
//variables
int index;
private String name;
private Tree[] arrayOfTrees;
public Forest(String forestName){
//Constructor class that takes a name and creates an array of trees().
index = 0;
name = forestName;
arrayOfTrees = new Tree[MAX_NUM_TREES];
for(index = 0; index < arrayOfTrees.length; index++){
arrayOfTrees[index] = new Tree();
}
}
public void display(){
// displays the array of trees and the index
index = 0;
if(name != null){
System.out.println(name);
for(index = 0; index < arrayOfTrees.length; index ++){
System.out.printf("%2d : %s\n", (index + 1), arrayOfTrees[index]);
}
}else{
System.out.println("No forest.");
}
}
public void yearGrowth(){
//grows each tree in the array
index = 0;
for(index = 0; index < arrayOfTrees.length ; index ++){
arrayOfTrees[index].grow();
}
}
public void reap(int reapHeight){
//reaps the trees and prints out the old and new information
index = 0;
for(index = 0; index < arrayOfTrees.length; index++){
if(arrayOfTrees[index].getHeight() >= reapHeight){
System.out.println("Cut " + (index+1) + " : " + arrayOfTrees[index] );
arrayOfTrees[index] = new Tree();
System.out.println("New " + (index+1) + " : " + arrayOfTrees[index] );
}
}
}
public static void saveForest(Forest forest) throws IOException {
//saves the forest
String name = forest.getName();
ObjectOutputStream toStream;
toStream = new ObjectOutputStream(new FileOutputStream(name));
toStream.writeObject(forest);
toStream.close();
}
public static Forest loadForest(String fileName) throws IOException {
//loads the forest
ObjectInputStream fromStream = null;
Forest local;
fromStream = new ObjectInputStream(new FileInputStream(fileName));
try {
local = (Forest)fromStream.readObject();
}catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
return(null);
}finally{
try {
if (fromStream != null) {
fromStream.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
return(null);
}
}
return(local);
}
public String getName(){
return (name);
}
}
Class2
import java.util.Random;
import java.util.*;
import java.io.*;
public class Tree{
//creates the variables as the
private double height;
private double growthRate;
private static Random rand = new Random();
final double MIN_HEIGHT = 1;
final double MIN_GROWTH_RATE = 0.5;
final double MAX_HEIGHT = 5;
final double MAX_GROWTH_RATE = 1.0;
public Tree() {
//creates tree with a height and a growth rate
Random rand = new Random();
height = (MIN_HEIGHT + ((Math.random() * (MAX_HEIGHT - MIN_HEIGHT))));
growthRate = (MIN_GROWTH_RATE + (Math.random() * (MAX_GROWTH_RATE - MIN_GROWTH_RATE)));
}
public double grow(){
//tree grows and returns height
height = height * (1 + growthRate);
return height;
}
public double getHeight(){
return (height);
}
public double getGrowthRate(){
return (growthRate);
}
public String toString(){
//toString formats the output with height and growthrate
return (String.format("%7.2f (%2d%% pa)", height, ((int)(growthRate * 100))));
}
}
If by serialization you understand standard java serialization with ObjectXXXStream, then yes, you can avoid it.
If you mean serialization in more broad way, then no. Files cant directly store java objects you have to convert them to bytes (which is serialization by definition).
PS: If you actually ask "How?" you should include it in your question.
I am currently working on a program where I take information from a text document, then I print it out into another file and from java but halfway through, i'm getting an no such exception error and i'm not sure why.
Tester code:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class HurricaneSelectorTester
{
public static void main (String [ ] args) throws IOException
{
//File scanner
File fileName = new File("HurricaneData.txt");
Scanner inFile = new Scanner(fileName);
PrintWriter outputFile = new PrintWriter(new File("OutputData.txt"));
Scanner in;
in = new Scanner(System.in);
//construct a Scanner object with one line
//Declare variables
int arrayLength = 156;
int [] years = new int[156];
int index = 0;
int cat1 = 0;
int cat2 = 0;
int cat3 = 0;
int cat4 = 0;
int cat5 = 0;
double windAvg = 0;
double windTotal = 0;
double windMax = Integer.MIN_VALUE;
double windMin = Integer.MAX_VALUE;
double pressureAvg = 0;
double pressureTotal = 0;
int pressureMax = Integer.MIN_VALUE;
int pressureMin = Integer.MAX_VALUE;
double catAvg = 0;
double catTotal = 0;
int catMax = Integer.MIN_VALUE;
int catMin = Integer.MAX_VALUE;
int rangeMax = 0;
int rangeMin = 0;
//Ask for range
System.out.println("Please enter minimum year (1995-2015)");
rangeMin = in.nextInt();
System.out.println("Please enter maximum year (1995-2015)");
rangeMax = in.nextInt();
//Print title info
System.out.println("Hurricanes "+ ""+ rangeMin + "-" + "" + rangeMax);
System.out.println();
System.out.println("Year Hurricane Category Pressure (mb) Wind Speed (mph)");
System.out.println("****************************************************************");
ArrayList<HurricaneSelector> hurricanes = new ArrayList<HurricaneSelector>();
//Load all the info into the arrays
while (inFile.hasNext())
{
hurricanes.add(new HurricaneSelector(inFile.nextInt(),inFile.next(),inFile.nextInt(),inFile.nextInt(),inFile.next()));
}
for(index = 0; index < 156; index++){
years[index] = inFile.nextInt();
}
inFile.close();
HurricaneSelector dataRecord; //Data record for HurricaneSelector
for(index = 0; index < 156; index++)
{if(years[index]>= rangeMin && years[index]<= rangeMax){
dataRecord = hurricanes.get(index);
dataRecord.calcCategoriesAndTotals();
dataRecord.calcNewWind();
dataRecord.calcWindMax();
dataRecord.calcWindMin();
dataRecord.calcPressureMax();
dataRecord.calcPressureMin();
dataRecord.calcCategoryMax();
dataRecord.calcCategoryMin();
}
}
dataRecord = hurricanes.get(index);
dataRecord.calcWindAverage();
dataRecord.calcCategoryAverage();
dataRecord.calcPressureAverage();
//Print out data
outputFile.println("Year Name Category Pressure Wind Speed");
for (index = 0; index < 156; index++){
if(years[index]>= rangeMin && years[index]<= rangeMax){
System.out.println(" "+hurricanes.get(index));
System.out.println();
outputFile.println(" "+hurricanes.get(index));
}
}
outputFile.close();
System.out.println("****************************************************************");
System.out.print(" Average:");
System.out.printf("%15.1f%13.1f%20.2f",catAvg,pressureAvg,windAvg);
System.out.println();
System.out.print(" Maximum:");
System.out.printf("%15d%13d%20.2f",catMax , pressureMax , windMax);
System.out.println();
System.out.print(" Minimum:");
System.out.printf("%15d%13d%20.2f",catMin , pressureMin , windMin);
System.out.println();
System.out.println();
System.out.println("Summary of categories");
System.out.println(" Category 1: " + cat1);
System.out.println(" Category 2: " + cat2);
System.out.println(" Category 3: " + cat3);
System.out.println(" Category 4: " + cat4);
System.out.println(" Category 5: " + cat5);
}
Methods:
public class HurricaneSelector
{
private int myYear, myPressure, myWind, myRangeMin, myRangeMax, myCategory, category1, category2,category3, category4, category5;
private String myMonth, myName;
private double myNewWind;
public double myWindAverage, myPressureAverage, myCategoryAverage, myWindMax = Integer.MIN_VALUE,
myWindMin = Integer.MAX_VALUE, myPressureMax = Integer.MIN_VALUE, myPressureMin = Integer.MAX_VALUE,
myCatMax = Integer.MIN_VALUE,myCatMin = Integer.MAX_VALUE;
public int total;
/**
* Constructor for objects of type HurricaneSelector
* #param year is the year of the hurricane
* #param month is the month of the hurricane
* #param pressure is the pressure of the hurricane
* #param wind is the wind speed of the hurricane
* #param name is the name of the hurricane
*/
HurricaneSelector(int year, String month, int pressure, int wind, String name)
{
myYear = year;
myMonth = month;
myPressure = pressure;
myWind = wind;
myName = name;
}
/**
* Mutator method to calculate the wind speed in mph (no parameters)
*/
public void calcNewWind()
{
myNewWind = (myWind* 1.15);
}
/**
* Mutator method to calculate if the value is the new Maximum (no parameters)
*/
public void calcWindMax()
{
if (myNewWind > myWindMax){
myWindMax = myNewWind;
}
}
/**
* Mutator method to calculate if the value is the new Minimum (no parameters)
*/
public void calcWindMin()
{
if (myNewWind > myWindMin){
myWindMin = myNewWind;
}
}
/**
* Mutator method to calculate if the value is the new Maximum (no parameters)
*/
public void calcPressureMax()
{
if (myPressure > myPressureMax){
myPressureMax = myPressure;
}
}
/**
* Mutator method to calculate if the value is the new Minimum (no parameters)
*/
public void calcPressureMin()
{
if (myPressure > myPressureMin){
myPressureMin = myPressure;
}
}
/**
* Mutator method to calculate if the value is the new Maximum (no parameters)
*/
public void calcCategoryMax()
{
if (myCategory > myCatMax){
myCatMax = myCategory;
}
}
/**
* Mutator method to calculate if the value is the new Minimum (no parameters)
*/
public void calcCategoryMin()
{
if (myCategory > myCatMin){
myCatMin = myCategory;
}
}
/**
* Mutator method to calculate which category the Hurricane fits into and get the totals(no parameters)
*/
public void calcCategoriesAndTotals()
{
myWindAverage += myNewWind;
myPressureAverage += myPressure;
if (myNewWind > 74 && myNewWind < 95)
{
myCategory = 1;
myCategoryAverage += myCategory;
category1++;
}
else if(myNewWind > 96 && myNewWind < 110)
{
myCategory = 2;
myCategoryAverage += myCategory;
category2++;
}
else if(myNewWind > 111 && myNewWind < 129)
{
myCategory = 3;
myCategoryAverage += myCategory;
category3++;
}
else if(myNewWind > 130 && myNewWind < 156)
{
myCategory = 4;
myCategoryAverage += myCategory;
category4++;
}
else if(myNewWind > 157)
{
myCategory = 5;
myCategoryAverage += myCategory;
category5++;
}
total++;
}
/**
* Mutator method to calculate the wind speed average (no parameters)
*/
public void calcWindAverage()
{
myWindAverage = myWindAverage/total;
}
/**
* Mutator method to calculate the category average (no parameters)
*/
public void calcCategoryAverage()
{
myCategoryAverage = myCategoryAverage/total;
}
/**
* Mutator method to calculate the pressure average (no parameters)
*/
public void calcPressureAverage()
{
myPressureAverage = myPressureAverage/total;
}
/**
* Getter method to return the year of the hurricane (no parameters)
*/
public int getYear()
{
return myYear;
}
/**
* Getter method to return the month of the hurricane (no parameters)
*/
public String getMonth()
{
return myMonth;
}
/**
* Getter method to return the pressure of the hurricane (no parameters)
*/
public int getPressure()
{
return myPressure;
}
/**
* Getter method to return the wind speed of the hurricane (no parameters)
*/
public double getNewWind()
{
return myNewWind;
}
/**
* Getter method to return the name of the hurricane (no parameters)
*/
public String getName()
{
return myName;
}
/**
* Getter method to return the wind average (no parameters)
*/
public Double getWindAverage()
{
return myWindAverage;
}
/**
* Getter method to return the pressure average (no parameters)
*/
public Double getPressureAverage()
{
return myPressureAverage;
}
/**
* Getter method to return the category average (no parameters)
*/
public Double getCategoryAverage()
{
return myCategoryAverage;
}
/**
* Getter method to return the category maximum (no parameters)
*/
public Double getWindMax()
{
return myWindMax;
}
/**
* Getter method to return the category minimum (no parameters)
*/
public Double getWindMin()
{
return myWindMin;
}
/**
* Getter method to return the category maximum (no parameters)
*/
public Double getPressureMax()
{
return myPressureMax;
}
/**
* Getter method to return the category minimum (no parameters)
*/
public Double getPressureMin()
{
return myPressureMin;
}
/**
* Getter method to return the category maximum (no parameters)
*/
public Double getCategoryMax()
{
return myCatMax;
}
/**
* Getter method to return the category minimum (no parameters)
*/
public Double getCategoryMin()
{
return myCatMax;
}
public String toString(){
return String.format("%10d%10s%10d%10d%10.2f",myYear,myName, myCategory, myPressure, myNewWind);
}
The links to the text files: https://drive.google.com/file/d/1eazHCEwT0Se6hfx2SDilqCqY8ZMi4E9k/view?usp=sharing
https://drive.google.com/file/d/1CN0JnlbMWNEB7B4nomgJ_-6mkwR1wgYc/view?usp=sharing
I know there are other problems with the code such as useless variables, formatting, etc. but right now I need to fix the program so that it can actually run and print out most of the data right now.
You need to reset() the Scanner because you've reached the end in your loop, and you want to start from the beginning for the next set of operations.
From JavaSE docs:
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
I am programming a very basic bot for planet wars in java and I cant seem to find the errors in my code. I am receiving a few different error messages but the main issue for me is the error: class, interface, or enum expected. Ive checked my brackets about a thousand times. Any help would be appreciated. Here's my bot code:
import java.util.List;
import java.util.Random;
import shared.Planet;
import shared.PlanetWars;
public class MyNewBot {
public static void doTurn(PlanetWars pw) {
// (1) If we currently have a fleet in flight, then do nothing until
// it arrives.
if (pw.myFleets().size() >= 10) {
return;
}
// (2) Pick one of my planets based on the number of ships
Planet source = null;
int largestForce = 0;
for (Planet p : pw.myPlanets()){
int force = pw.numShips();
if( force > largestForce){
largestForce = force;
source = p;
}
}
// (3) Pick a target planet at random.
Planet dest = null;
int highestGrowthRate = 0;
int shortestDistance = 9999;
for (Planet p = pw.notMyPlanets()){
int growthRate = pw.growthRate();
if( growthRate > highestGrowthRate){
highestGrowthRate = growthRate;
dest = p;
}else if (growthRate == highestGrowthRate){
int distance = pw.distance(source,p);
if (distance < shortestDistance){
shortestDistance = distance;
dest = p;
}
}
}
// (4) Send half the ships from source to destination.
if (source != null && dest != null) {
int numShips = source.numShips() / 2;
pw.issueOrder(source, dest, numShips);
}
}
// Ignore the main method unless you know what you're doing.
// Refer to the doTurn function to code your bot.
public static void main(String[] args) {
String line = "";
String message = "";
int c;
try {
while ((c = System.in.read()) >= 0) {
switch (c) {
case '\n':
if (line.equals("go")) {
PlanetWars pw = new PlanetWars(message);
doTurn(pw);
pw.finishTurn();
message = "";
} else {
message += line + "\n";
}
line = "";
break;
default:
line += (char) c;
break;
}
}
} catch (Exception e) {
// Owned.
}
}
}
and the supporting class files:
package shared;
public class Planet implements Cloneable {
private int planetID;
private int owner;
private int numShips;
private int growthRate;
private double x, y;
public Planet(int planetID, int owner, int numShips, int growthRate,
double x, double y) {
this.planetID = planetID;
this.owner = owner;
this.numShips = numShips;
this.growthRate = growthRate;
this.x = x;
this.y = y;
}
public int planetID() {
return planetID;
}
public int owner() {
return owner;
}
public int numShips() {
return numShips;
}
public int growthRate() {
return growthRate;
}
public double x() {
return x;
}
public double y() {
return y;
}
public void owner(int newOwner) {
this.owner = newOwner;
}
public void numShips(int newNumShips) {
this.numShips = newNumShips;
}
public void addShips(int amount) {
numShips += amount;
}
public void removeShips(int amount) {
numShips -= amount;
}
private Planet(Planet _p) {
planetID = _p.planetID;
owner = _p.owner;
numShips = _p.numShips;
growthRate = _p.growthRate;
x = _p.x;
y = _p.y;
}
public Object clone() {
return new Planet(this);
}
}
package shared;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PlanetWars {
// Constructs a PlanetWars object instance, given a string containing a
// description of a game state.
public PlanetWars(String gameStateString) {
planets = new ArrayList<Planet>();
fleets = new ArrayList<Fleet>();
parseGameState(gameStateString);
}
// Returns the number of planets. Planets are numbered starting with 0.
public int numPlanets() {
return planets.size();
}
// Returns the planet with the given planet_id. There are NumPlanets()
// planets. They are numbered starting at 0.
public Planet getPlanet(int planetID) {
return planets.get(planetID);
}
// Returns the number of fleets.
public int numFleets() {
return fleets.size();
}
// Returns the fleet with the given fleet_id. Fleets are numbered starting
// with 0. There are NumFleets() fleets. fleet_id's are not consistent from
// one turn to the next.
public Fleet getFleet(int fleetID) {
return fleets.get(fleetID);
}
// Returns a list of all the planets.
public List<Planet> planets() {
return planets;
}
// Return a list of all the planets owned by the current player. By
// convention, the current player is always player number 1.
public List<Planet> myPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() == 1) {
r.add(p);
}
}
return r;
}
// Return a list of all neutral planets.
public List<Planet> neutralPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() == 0) {
r.add(p);
}
}
return r;
}
// Return a list of all the planets owned by rival players. This excludes
// planets owned by the current player, as well as neutral planets.
public List<Planet> enemyPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() >= 2) {
r.add(p);
}
}
return r;
}
// Return a list of all the planets that are not owned by the current
// player. This includes all enemy planets and neutral planets.
public List<Planet> notMyPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() != 1) {
r.add(p);
}
}
return r;
}
// Return a list of all the fleets.
public List<Fleet> fleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
r.add(f);
}
return r;
}
// Return a list of all the fleets owned by the current player.
public List<Fleet> myFleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
if (f.owner() == 1) {
r.add(f);
}
}
return r;
}
// Return a list of all the fleets owned by enemy players.
public List<Fleet> enemyFleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
if (f.owner() != 1) {
r.add(f);
}
}
return r;
}
// Returns the distance between two planets, rounded up to the next highest
// integer. This is the number of discrete time steps it takes to get
// between the two planets.
public int distance(int sourcePlanet, int destinationPlanet) {
Planet source = planets.get(sourcePlanet);
Planet destination = planets.get(destinationPlanet);
double dx = source.x() - destination.x();
double dy = source.y() - destination.y();
return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
}
// Returns the distance between two planets, rounded up to the next highest
// integer. This is the number of discrete time steps it takes to get
// between the two planets.
public int distance(Planet source, Planet destination) {
double dx = source.x() - destination.x();
double dy = source.y() - destination.y();
return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void issueOrder(int sourcePlanet, int destinationPlanet, int
numShips) {
System.out.println("" + sourcePlanet + " " + destinationPlanet + " "
+ numShips);
System.out.flush();
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void issueOrder(Planet source, Planet dest, int numShips) {
System.out.println("" + source.planetID() + " " + dest.planetID() + " "
+ numShips);
System.out.flush();
}
// Sends the game engine a message to let it know that we're done sending
// orders. This signifies the end of our turn.
public void finishTurn() {
System.out.println("go");
System.out.flush();
}
// Returns true if the named player owns at least one planet or fleet.
// Otherwise, the player is deemed to be dead and false is returned.
public boolean isAlive(int playerID) {
for (Planet p : planets) {
if (p.owner() == playerID) {
return true;
}
}
for (Fleet f : fleets) {
if (f.owner() == playerID) {
return true;
}
}
return false;
}
// If the game is not yet over (ie: at least two players have planets or
// fleets remaining), returns -1. If the game is over (ie: only one player
// is left) then that player's number is returned. If there are no
// remaining players, then the game is a draw and 0 is returned.
public int winner() {
Set<Integer> remainingPlayers = new TreeSet<Integer>();
for (Planet p : planets) {
remainingPlayers.add(p.owner());
}
for (Fleet f : fleets) {
remainingPlayers.add(f.owner());
}
switch (remainingPlayers.size()) {
case 0:
return 0;
case 1:
return ((Integer) remainingPlayers.toArray()[0]).intValue();
default:
return -1;
}
}
// Returns the number of ships that the current player has, either located
// on planets or in flight.
public int numShips(int playerID) {
int numShips = 0;
for (Planet p : planets) {
if (p.owner() == playerID) {
numShips += p.numShips();
}
}
for (Fleet f : fleets) {
if (f.owner() == playerID) {
numShips += f.numShips();
}
}
return numShips;
}
// Returns the production of the given player.
public int production(int playerID) {
int prod = 0;
for (Planet p : planets) {
if (p.owner() == playerID) {
prod += p.growthRate();
}
}
return prod;
}
// Parses a game state from a string. On success, returns 1. On failure,
// returns 0.
private int parseGameState(String s) {
planets.clear();
fleets.clear();
int planetID = 0;
String[] lines = s.split("\n");
for (int i = 0; i < lines.length; ++i) {
String line = lines[i];
int commentBegin = line.indexOf('#');
if (commentBegin >= 0) {
line = line.substring(0, commentBegin);
}
if (line.trim().length() == 0) {
continue;
}
String[] tokens = line.split(" ");
if (tokens.length == 0) {
continue;
}
if (tokens[0].equals("P")) {
if (tokens.length != 6) {
return 0;
}
double x = Double.parseDouble(tokens[1]);
double y = Double.parseDouble(tokens[2]);
int owner = Integer.parseInt(tokens[3]);
int numShips = Integer.parseInt(tokens[4]);
int growthRate = Integer.parseInt(tokens[5]);
Planet p = new Planet(planetID++, owner, numShips, growthRate,
x, y);
planets.add(p);
} else if (tokens[0].equals("F")) {
if (tokens.length != 7) {
return 0;
}
int owner = Integer.parseInt(tokens[1]);
int numShips = Integer.parseInt(tokens[2]);
int source = Integer.parseInt(tokens[3]);
int destination = Integer.parseInt(tokens[4]);
int totalTripLength = Integer.parseInt(tokens[5]);
int turnsRemaining = Integer.parseInt(tokens[6]);
Fleet f = new Fleet(owner, numShips, source, destination,
totalTripLength, turnsRemaining);
fleets.add(f);
} else {
return 0;
}
}
return 1;
}
// Store all the planets and fleets. OMG we wouldn't wanna lose all the
// planets and fleets, would we!?
private ArrayList<Planet> planets;
private ArrayList<Fleet> fleets;
}
package shared;
public class Fleet implements Comparable<Fleet>, Cloneable {
private int owner;
private int numShips;
private int sourcePlanet;
private int destinationPlanet;
private int totalTripLength;
private int turnsRemaining;
public Fleet(int owner, int numShips, int sourcePlanet,
int destinationPlanet, int totalTripLength, int turnsRemaining) {
this.owner = owner;
this.numShips = numShips;
this.sourcePlanet = sourcePlanet;
this.destinationPlanet = destinationPlanet;
this.totalTripLength = totalTripLength;
this.turnsRemaining = turnsRemaining;
}
public Fleet(int owner, int numShips) {
this.owner = owner;
this.numShips = numShips;
this.sourcePlanet = -1;
this.destinationPlanet = -1;
this.totalTripLength = -1;
this.turnsRemaining = -1;
}
public int owner() {
return owner;
}
public int numShips() {
return numShips;
}
public int sourcePlanet() {
return sourcePlanet;
}
public int destinationPlanet() {
return destinationPlanet;
}
public int totalTripLength() {
return totalTripLength;
}
public int turnsRemaining() {
return turnsRemaining;
}
public void removeShips(int amount) {
numShips -= amount;
}
// Subtracts one turn remaining. Call this function to make the fleet get
// one turn closer to its destination.
public void TimeStep() {
if (turnsRemaining > 0) {
--turnsRemaining;
} else {
turnsRemaining = 0;
}
}
#Override
public int compareTo(Fleet f) {
return this.numShips - f.numShips;
}
private Fleet(Fleet _f) {
owner = _f.owner;
numShips = _f.numShips;
sourcePlanet = _f.sourcePlanet;
destinationPlanet = _f.destinationPlanet;
totalTripLength = _f.totalTripLength;
turnsRemaining = _f.turnsRemaining;
}
public Object clone() {
return new Fleet(this);
}
}
for (Planet p = pw.notMyPlanets()){ should be for (Planet p : pw.notMyPlanets()){.
You've not posted the Fleet class, so as it is the code won't compile for me. However, the above is the only other error I could see.
I am new to java and am currently creating a program where I calculate various amounts of money (tax, gross pay, etc) using overload methods and then display it. I have completed the bulk of it (I think), but now I need to create a second class in the same package where I set values to the first program to see if it works. I have no idea how to call the method when overload methods are involved, I tried to use get and set but I don't know how to apply that in the overload method. I apologize if my terminology is off, I'm still quite new!
package payrolllibrary;
public class PayrollLibrary {
public static float calculatePay(float hours, float rates)
{System.out.println("Pay: " + rates*hours);
return 0;
}
public static float calculatePay(float hours, float rates, float multiplier)
{System.out.println("Pay: " + rates*hours*multiplier);
return 0;
}
public static float calculateGrossPay(float regularPay, float overtimePay, float shift2Pay, float shift3Pay, float weeklyPay)
{float grossPay;
grossPay = regularPay + overtimePay + shift2Pay + shift3Pay + weeklyPay;
System.out.println("Gross Pay: " + grossPay);
return 0;
}
public static float calculatedSocialSecurityTax(float grossPay, float ytdEarnings, float ytdSocialSecurity)
{
float calculateSocialSecurityTax = 0;
float calculateGrossPay = 0;
if(ytdEarnings > 118500)
{calculateSocialSecurityTax = 0;}
if (ytdEarnings+calculateGrossPay < 118500)
{calculateSocialSecurityTax = calculateGrossPay*.062f;}
if (ytdEarnings+calculateGrossPay > 118500)
{if (calculateGrossPay*.062 <= 118500)
{calculateSocialSecurityTax = 118500;}
}
{System.out.println("Social Security Tax: " + calculateSocialSecurityTax);
return 0;
}
}
public static float calculateMedicareTax(float grossPay)
{float medicareTax;
medicareTax = grossPay*.0145f;
System.out.println("Medicare Tax: " + medicareTax);
return 0;
}
public static float calculateStateTax(float grossPay, float stateWithholding)
{System.out.println("State Tax: " + grossPay*stateWithholding);
return 0;
}
public static float calculateNetPay(float grossPay, float federalWithholding, float socialSecurityWithholding, float medicareWithholding, float stateWithholding, float deduction1Amount, float deduction2Amount, float deduction3Amount)
{float calculateNetPay;
calculateNetPay = grossPay-federalWithholding-socialSecurityWithholding-medicareWithholding-stateWithholding-deduction1Amount-deduction2Amount-deduction3Amount;
System.out.println("Net Pay: " + calculateNetPay);
return 0;
}
public static float calculateDeduction(float grossPay, char deductionCode, float deductionValue)
{if (deductionCode == 'N')
{deductionValue = 0;}
else if (deductionCode == 'F')
{deductionValue = deductionValue;}
else if (deductionCode == 'P')
{deductionValue = deductionValue*grossPay;}
System.out.println("Deduction: " + deductionValue);
return 0;
}
}
package PayrollLibrary;
public class TestPayroll {
public static void main(String[] args) {
PayrollLibrary Person = new PayrollLibrary();
Person.setRate(99.99);
Person.setHours(99);
Person.setMultiplier(999);
Person.setRegularPay(999);
Person.setOvertimePay(999);
Person.setShift2Pay(999);
Person.setShift3Pay(999);
Person.setWeekendPay(999);
Person.setYtdEarnings(999);
Person.setYtdSocialSecurity(999);
Person.setStateWithholding(999);
Person.setDeduction1Amount(999);
Person.setDeduction2Amount(999);
Person.setDeduction3Amount(999);
Person.setDeductionCode('F');
Person.setDeductionAmount(999);
}
}
Those setXXX() won't set the values just because their English meaning are so. They are just names of methods. To set the values you have to code them. So in your PayrollLibrary you should have
public class PayrollLibrary {
float rate;
float hours;
......
public void setRate(float inRate) {
this.rate = inRate;
}
public void setHours(float inHours) {
this.hours = inHours;
}
Then in your calculation methods, if what you going to use are rate and hours, you don't have to pass them to the method, simply:
public float calculatePay() {
return rate*hours;
}
So in your main(), do this:
PayrollLibrary person = new PayrollLibrary();
person.setRate(99.99f);
person.setHours(99.0f);
to obtain the pay right after the setXXX above, do this:
float thePay = person.calculatePay();
Please note the Java convention: class names starts in upper case, variable and method names start in lower case.
Hope it helps.
I am working on a Java program called Namesurfer for a home assignment. The program consists of five classes: 'NameSurfer, NameSurferConstants, NameSurferDataBase, NameSurferEntry, and NameSurferGraph.
The code is (I thought) complete, but when I put the name on NameSurfer console and press enter, I get the following error. And when I click Graph, it doesn't do anything.
My suspicion is it has something to do with NameSurferEntry class, but I've been looking for hours without success. I'm really new at Java, and any help will be appreciated.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at NameSurfer.actionPerformed(NameSurfer.java:58)
at javax.swing.JTextField.fireActionPerformed(JTextField.java:492)
at javax.swing.JTextField.postActionEvent(JTextField.java:705)
at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:820)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1645)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2859)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2894)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2822)
at java.awt.Component.processEvent(Component.java:6159)
at java.awt.Container.processEvent(Container.java:2083)
at java.awt.Component.dispatchEventImpl(Component.java:4744)
at java.awt.Container.dispatchEventImpl(Container.java:2141)
at java.awt.Component.dispatchEvent(Component.java:4572)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1856)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:722)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1000)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:865)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:686)
at java.awt.Component.dispatchEventImpl(Component.java:4616)
at java.awt.Container.dispatchEventImpl(Container.java:2141)
at java.awt.Window.dispatchEventImpl(Window.java:2489)
at java.awt.Component.dispatchEvent(Component.java:4572)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:710)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:669)
at java.awt.EventQueue$2.run(EventQueue.java:667)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$3.run(EventQueue.java:683)
at java.awt.EventQueue$3.run(EventQueue.java:681)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:680)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Here's the code for NameSurfer.
/*
* File: NameSurfer.java
* ---------------------
* When it is finished, this program will implements the viewer for
* the baby-name database described in the assignment handout.
*/
import acm.program.*;
import java.awt.event.*;
import javax.swing.*;
public class NameSurfer extends Program implements NameSurferConstants {
/* private instance variables*/
private JButton graphButton;
private JButton clearButton;
private JLabel nameLabel;
private JTextField name;
private NameSurferGraph graph;
private NameSurferDataBase dataBase;
/**
* This method has the responsibility for reading in the data base
* and initializing the interactors at the top of the window.
*/
public void init() {
addActionListeners();
graph = new NameSurferGraph();
add(graph);
/* adds the control bar*/
nameLabel = new JLabel ("Name");
add(nameLabel, NORTH);
name = new JTextField(MAX_FONT_NAME);
name.addActionListener(this);
add(name, NORTH);
graphButton = new JButton ("Graph");
add(graphButton, NORTH);
clearButton = new JButton ("Clear");
add(clearButton, NORTH);
}
/**
* This class is responsible for detecting when the buttons are
* clicked, so you will have to define a method to respond to
* button actions.
*/
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals ("Clear")) {
graph.clear();
graph.update();
} else {
String inputName = name.getText();
NameSurferEntry entry = dataBase.findEntry(inputName);
if (entry != null) {
graph.addEntry(entry);
graph.update();
}
}
}
}
And here's the code for NameSurferEntry.
/*
* File: NameSurferEntry.java
* --------------------------
* This class represents a single entry in the database. Each
* NameSurferEntry contains a name and a list giving the popularity
* of that name for each decade stretching back to 1900.
*/
import acm.util.*;
import java.util.*;
import java.util.StringTokenizer;
public class NameSurferEntry implements NameSurferConstants {
/* private instance variables*/
private String name;
private int[] ranks = new int [NDECADES];
/**
* Creates a new NameSurferEntry from a data line as it appears
* in the data file. Each line begins with the name, which is
* followed by integers giving the rank of that name for each
* decade.
*/
public NameSurferEntry(String line) {
//gets the name
int nameEnd = line.indexOf(" ");
name = line.substring(0, nameEnd);
//gets the ranking and forms it into an array using StringTokenizer class
String rankingStart = line.substring(nameEnd + 1);
StringTokenizer tokenizer = new StringTokenizer(rankingStart);
for (int i = 0; tokenizer.hasMoreTokens(); i++) {
int yearRank = Integer.parseInt(tokenizer.nextToken());
ranks[i] = yearRank;
}
}
/* Method: getName() */
/**
* Returns the name associated with this entry.
*/
public String getName() {
return name;
}
/* Method: getRank(decade) */
/**
* Returns the rank associated with an entry for a particular
* decade. The decade value is an integer indicating how many
* decades have passed since the first year in the database,
* which is given by the constant START_DECADE. If a name does
* not appear in a decade, the rank value is 0.
*/
public int getRank(int decade) {
if (decade <NDECADES) {
return ranks[decade];
}
return 0;
}
/* Method: toString() */
/**
* Returns a string that makes it easy to see the value of a
* NameSurferEntry.
*/
public String toString() {
String result = "";
for (int i = 0; i < ranks.length; i++) {
result += getRank(i);
}
return ("\"" + name + "[" + result + "]\"");
}
}
And here's the code for NameSurferGraph.
import acm.graphics.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
public class NameSurferGraph extends GCanvas implements NameSurferConstants, ComponentListener {
/*Private instance variables*/
private ArrayList <NameSurferEntry> dataDisplay;
/**
* Creates a new NameSurferGraph object that displays the data.
*/
public NameSurferGraph() {
addComponentListener(this);
dataDisplay = new ArrayList<NameSurferEntry>();
}
/**
* Clears the list of name surfer entries stored inside this class.
*/
public void clear() {
dataDisplay.clear();
update();
}
/**
* Adds a new NameSurferEntry to the list of entries on the display.
* Note that this method does not actually draw the graph, but
* simply stores the entry; the graph is drawn by calling update.
*/
public void addEntry(NameSurferEntry entry) {
dataDisplay.add(entry);
}
/**
* Updates the display image by deleting all the graphical objects
* from the canvas and then reassembling the display according to
* the list of entries. Your application must call update after
* calling either clear or addEntry; update is also called whenever
* the size of the canvas changes.
*/
public void update() {
removeAll();
drawGraph();
if (dataDisplay.size() >= 0) {
for (int i = 0; i < dataDisplay.size(); i++) {
NameSurferEntry entry = dataDisplay.get(i);
drawRankingGraph (entry, i);
}
}
}
/*draws the background grids and displays the years*/
private void drawGraph() {
drawMargins();
drawVerticalLines();
displayYears();
}
/*Draws the horizontal lines at the top and the bottom of the window*/
private void drawMargins() {
double x1 = 0;
double x2 = getWidth();
double y1 = GRAPH_MARGIN_SIZE;
double y2 = getHeight() - GRAPH_MARGIN_SIZE;
GLine topLine = new GLine (x1, y1, x2, y1);
GLine bottomLine = new GLine (x1, y2, x2, y2);
add(topLine);
add(bottomLine);
}
/*Draws the vertical lines*/
private void drawVerticalLines() {
double x = 0;
for (int i = 0; i < NDECADES; i++) {
GLine verticalLine = new GLine (x, 0, x, getHeight());
x += getWidth() / NDECADES;
add(verticalLine);
}
}
/*Displays the years*/
private void displayYears() {
int decade = START_DECADE;
double x = 0;
for (int i = 0; i < NDECADES; i++) {
GLabel label = new GLabel ("" + decade);
add(label, x, getHeight() - GRAPH_MARGIN_SIZE/2 + (label.getAscent() / 2));
decade += NUMBER_OF_YEARS;
x += getWidth() / NDECADES;
}
}
/*Draws the ranking graph and the input name label*/
private void drawRankingGraph(NameSurferEntry entry, int n) {
int inputOrder = n;
for (int i = 0; i < NDECADES - 1; i++) {
int r1 = entry.getRank(i);
int r2 = entry.getRank(i + 1);
double x1 = i * (getWidth()/NDECADES);
double x2 = (i+1) * (getWidth()/NDECADES);
double y1 = 0;
double y2 = 0;
if (r1 == 0) {
y1 = getHeight() - GRAPH_MARGIN_SIZE;
} else {
y1 = GRAPH_MARGIN_SIZE + (getHeight() - GRAPH_MARGIN_SIZE*2) * r1 / MAX_RANK;
}
if (r2 == 0) {
y2 = getHeight() - GRAPH_MARGIN_SIZE;
} else {
y2 = GRAPH_MARGIN_SIZE + (getHeight() - GRAPH_MARGIN_SIZE*2) * r2 / MAX_RANK;
}
/*Sets the graph and the label on the window*/
GLine rankingGraph = new GLine (x1, y1, x2, y2);
GLabel inputName = new GLabel(entry.getName() + " " + (entry.getRank(i) == 0 ? "*" : entry.getRank(i)));
/*Sets the color*/
Color color = getColor(inputOrder%4);
rankingGraph.setColor(color);
inputName.setColor(color);
/*Displays the graph and the label*/
add(rankingGraph);
add(inputName, x1, y2);
}
}
/*Gets the color of the rankingGraph and the inputName label*/
private Color getColor(int i) {
switch (i) {
case 0: return Color.black;
case 1: return Color.red;
case 2: return Color.blue;
}
return Color.magenta;
}
/* Implementation of the ComponentListener interface */
public void componentHidden(ComponentEvent e) { }
public void componentMoved(ComponentEvent e) { }
public void componentResized(ComponentEvent e) { update(); }
public void componentShown(ComponentEvent e) { }
}
Your "database" seems to be null.
Note that you either provided incomplete NameSurfer source or you need to recompile your application - line numbers are off, line 58 only has a closing brace.
Check the usage of "actionPerformed" method. You're probably trying to use it on something which is not set and therefore "null".
You're calling a method on an object that's null at NameSurfer.java:58 . Find out what can be null on that line and figure out why it's null even though you expect it not to be.
Unrelated to that, read up on the Java Naming Conventions. Only your type names should start with an uppercase.