Car class with acceleration and braking - java

I am in an intro to java class and I am having trouble with a car class that was assigned. Here are the instructions:
Write a class named Car that has the following fields (attributes):
yearModel (an int which hold's the car's year model)
make (a String which holds the make of the car)
speed (an int which holds the car's current speed)
The Car class should have the following constructor and other methods:
Constructor - Accepts the car's year model and make as arguments.
Accessors (getters) for the object's yearModel, make, and speed fields
Methods:
accelerate - each time it is called, it should add 5 to the speed field
brake - each time it is called, it should subtract 5 to the speed field
Write a Driver class, the DrivingSimulation class, which does the following:
Prompt the user for the yearModel, make, and speed values of a car.
Create a Car object
Call the accelerate method 5 times - after each call, use the accessor method to display the current speed of the car
Call the brake method 5 times - after each call, use the accessor method to display the current speed of the car
I got most of it done but it is not receiving the speed input that I am putting, and is instead starting from default, 0. Here is my car class
package drivingsimulation;
/**
*
* #author Carlos
*/
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make) {
this.yearModel = yearModel;
this.make = make;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
System.out.println("You are going " + speed + " mph");
return speed;
}
public void accelerate() {
speed += 5;
}
public void brake () {
speed-=5;
}
}
And here is my driver class:
/*
package drivingsimulation;
import java.util.Scanner;
/**
*
* #author Carlos
*/
public class DrivingSimulation {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int yearModel=0;
int speed=0;
String make=null;
Scanner keyboard = new Scanner (System.in);
Car myCar = new Car(yearModel, make);
System.out.println("What is the year of your car? ");
yearModel = keyboard.nextInt();
System.out.println("What is the make of your car? ");
make = keyboard.next();
System.out.println("How fast is your car going? ");
speed = keyboard.nextInt();
for(int i=0; i<5; i++){
myCar.accelerate();
}
}
}

Well you have a accessor for the speed class member but not setter for when you get the value from the user input in your driver class.
A method in your Car class like this:
public void setSpeed(int speed)
{
this.speed = speed;
}
Will the set value for the car instance was user input is given.
You can call it after the user input for speed like this..
myCar.setSpeed(speed);

How do you know it's not getting the speed information -- you never call getSpeed() on it.
Suggestions:
Call getSpeed() if you want to see what the speed is.
Get all println's out of the Car class. They should be in your main method only currently.
Give the class a setter method for speed -- public void setSpeed(int speed), and call the method.
For example, getSpeed() should be just
public int getSpeed() {
return speed;
}
That's it and nothing more. But you'd call it like:
System.out.println("Car's speed: " + myCar.getSpeed());
You also don't have a public void setSpeed(int speed) method, and you need one, and should call it after getting the information from the user.

Add a setSpeed() setter in your Car class and call it in your DrivingSimulation class like below (also move print statement to DrivingSimulation so your Car remains modularized).
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make) {
this.yearModel = yearModel;
this.make = make;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void accelerate() {
speed += 5;
}
public void brake () {
speed -= 5;
}
}
and...
import java.util.Scanner;
public class DrivingSimulation {
public static void main(String[] args) {
int yearModel = 0;
String make = null;
int speed;
Scanner keyboard = new Scanner(System.in);
Car car = new Car(yearModel, make);
System.out.println("What is the year of the car?");
yearModel = keyboard.nextInt();
System.out.println("What is the make of the car?");
keyboard.nextLine(); // fixes bug - receives the Enter key without skipping make = keyboard.nextLine()
make = keyboard.nextLine();
System.out.println("What speed is the initial speed of the car?");
speed = keyboard.nextInt();
car.setSpeed(speed);
for (int i = 0; i < 5; i ++) {
car.accelerate();
System.out.println("Your " + yearModel + " " + make +
" is traveling at " + car.getSpeed() + " MPH.");
}
}
}

Related

Connecting two classes

I'm stuck on this one exercise where I should create a second class called Car, that is linked to Vehicle. This is how it should look:
The vehicle class along with the testprogram works great, but now I want to connect the class Car to the vehicle, and then create a testclass for car. This is my vehicle class:
public class Vehicle {
int speed;
// Constructor
public Vehicle() {
this.speed = 0;
}
public class Car extends Vehicle {
String regnr;
public Car(String regnr) {
this.regnr = regnr;
}
public String getRegNbr() {
return this.regnr;
}
}
public void increaseSpeed(int differenceInc) {
int currentSpeed = this.speed;
// Kör loopen så länge den nuvarande hastigheten inte är lika med den önskade
while (this.speed != (currentSpeed + differenceInc)) {
this.speed += 1;
System.out.println("The current speed is increasing to: " + this.speed);
}
}
public void decreaseSpeed(int differenceDec) {
int currentSpeed = this.speed;
while (this.speed != (currentSpeed - differenceDec)) {
this.speed -= 1;
System.out.println("The current speed is decreasing to: " + this.speed);
}
}
public void brake() {
int currentSpeed = this.speed;
while (this.speed != 0) {
this.speed /= 2;
System.out.println("The current speed is decreasing to: " + this.speed);
}
}
public int getSpeed() {
return this.speed;
}
public void testVehicle() {
Scanner myScanner = new Scanner(System.in);
while (this.speed != 0) {
System.out.println("You're driving at: " + " " + this.speed + "KM/H" + "\n\nDo you want to:"
+ "\n(1) Slow down to " + "lower speed??" + "\n(2) Maintain current speed?"
+ "\n(3) Hit the brakes?" + "\n(4) Accelerate even more?");
int choice = myScanner.nextInt();
if (choice == 1) {
System.out.print("By how much would you like to decrease your speed? ");
Scanner in = new Scanner(System.in);
int dec = in.nextInt();
this.decreaseSpeed(dec);
} else if (choice == 2) {
System.out.println("Maintaining current speed");
} else if (choice == 3) {
System.out.println("Breaking!");
this.brake();
}
else if (choice == 4) {
System.out.print("By how much would you like to increase your speed? (km/h)");
Scanner in = new Scanner(System.in);
int inc = in.nextInt();
this.increaseSpeed(inc);
}
else {
System.err.println("Incorrect value entererd.");
System.exit(0);
}
}
if (this.getSpeed() == 0)
{
System.out.println("Bilen står still");
}
}
}
As you can see, the testVehicle() class along with a small separate test-program called VehicleTest runs the Vehicle class I created. I've added the Car-class to the program, and it extends vehicle as it should. The only question I have is how do I implement it into the test class?
My current separate test-program looks like this:
public class VehicleTest {
/**
* #param args
*/
public static void main(String[] args) {
Vehicle bmw = new Vehicle();
Scanner scan = new Scanner(System.in);
System.out.println("How fast do you want to drive?");
int fast = scan.nextInt();
bmw.increaseSpeed(fast);
bmw.testVehicle();
}
}
You should extend Car from Vehicle. Try this:
public class Car1 extends Vehicle {
...
}
Thus you may use Car like a Vehicle.
Some info to read https://books.trinket.io/thinkjava2/chapter14.html
Derive your Car1 class from Vehicle class
public class Car1 extends Vehicle{
String regnr;
public Car1(String regnr) {
super();//pass data to parent constructor if needed
this.regnr = regnr;
}
public String getRegNbr() {
return regnr;
}
}
Now you will be able to call public methods from Vehicle class.
Car1 car = new Car1("DHM1234");
car.increaseSpeed(5); // The current speed is increasing to: 5
if you want to change behavior of any public/protected methods of your vehicle (parent) class for your car class, override that method
i.e
#Override
public void brake() {
int currentSpeed = 0;
System.out.println("Hard break");
}
now if you call brake() from car object
car.brake(); // Hard break will be printed
Give Java Inheritance a read to learn more.

how to use abstract classes, and implementing them

I'm not sure how eloquently I can really explain what I don't understand/need help with, I'm still Very new to Object Oriented Programming. This is regarding my coursework and I don't expect anyone to do it for me, I just need help understanding how to move on, and if I'm even on the right track.
Ok, so on to my question. Basically, I am attempting to create an arraylist which will hold a few objects which themselves has a bunch of information(obviously), my spec said to create an abstract class, which will be extended by my constructor class, which I did. The abstract class has a few variables (decided by spec) But I dont know how to move them over to my extended class.
I'll post my code below, and I hope it makes sense. I'd be very thankful for any help you all could provide. I'm very confused right now.
Basically, I would love to know, A) How do I create an object in my arraylist which will be able to contain everything in SportsClub and FootballClub, and preferably all the variables user inputted.
And B) I don't know how to print The object, When I print right now I get coursework.FootballClub#49233bdc, Which I'm sure there's a reason for but I need the information in the objects to display, E.g. name. And if possible to sort the results by alphabetical order with respect to name? I hope this is all written ok. Sorry and Thank you in advance.
package coursework;
import java.util.*;
/**
*
* #author w1469384
*/
public class PremierLeagueManager implements LeagueManager{
public static void main(String[] args) {
Scanner c1 = new Scanner(System.in);
Scanner c2 = new Scanner(System.in);
ArrayList<FootballClub> PL = new ArrayList<FootballClub>();
int choice;
System.out.println("Enter 1; To create a club, 2; To Delete a Club, 3; To display all clubs and 99 to close the program");
choice = c1.nextInt();
//Creates and adds a new FootballClub Object
while (choice != 99){
if (choice == 1){
System.out.println("Please Enter The games played for the club");
int played = c1.nextInt();
System.out.println("Please enter the number of wins");
int wins = c1.nextInt();
System.out.println("please enter the number of losses");
int losses = c1.nextInt();
System.out.println("please enter the number of draws");
int draws = c1.nextInt();
System.out.println("please enter the number of goals for");
int goalsFor = c1.nextInt();
System.out.println("please enter the number of goals against");
int goalsAgainst = c1.nextInt();
FootballClub club = new FootballClub(played, wins, losses, draws, goalsFor, goalsAgainst);
PL.add(club);
System.out.println("check");
}
//Deletes a FootballClub Object
if (choice == 2){
}
//Displays all Football Clubs in the PremierLeague array
if (choice == 3){
System.out.println(PL);
}
//Closes the Program 1
choice = c1.nextInt();
}
}
}
public abstract class SportsClub {
public String name;
public String location;
public int capacity;
public void setName(String Name){
name = Name;
}
public void setLocation(String Location){
location = Location;
}
public void setCapacity(int Capacity){
capacity = Capacity;
}
public String getName(){
return name;
}
public String getLocation(){
return location;
}
public int getCapacity(){
return capacity;
}
}
public class FootballClub extends SportsClub {
//Statistics for the club.
int played;
int wins;
int losses;
int draws;
int goalsFor;
int goalsAgainst;
public FootballClub(int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst){
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
public void setPlayed(int newPlayed){
played = newPlayed;
}
public void setWins(int newWins){
wins = newWins;
}
public void setLosses(int newLosses){
losses = newLosses;
}
public void setDraws(int newDraws){
draws = newDraws;
}
public void setGoalsFor(int newGoalsFor){
goalsFor = newGoalsFor;
}
public void setGoalsAgainst(int newGoalsAgainst){
goalsAgainst = newGoalsAgainst;
}
public int getPlayed(){
return played;
}
public int getWins(){
return wins;
}
public int getLosses(){
return losses;
}
public int getDraws(){
return draws;
}
public int getGoalsFor(){
return goalsFor;
}
public int getGoalsAgainst(){
return goalsAgainst;
}
}
FootballClub inherits the variables declared in SportsClub so you can set them as you please.
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
// set the variables from the superclass
name = inName;
location = inLocation;
capacity = inCapacity;
}
FootballClub also inherits the methods declared in SportsClub so you can use the setters and getters too.
Normally you would create a constructor for SportsClub that sets these and then call that constructor from the FootballClub constructor.
// in SportsClub
protected SportsClub(
String inName, String inLocation, int inCapacity
) {
name = inName;
location = inLocation;
capacity = inCapacity;
}
// in FootballClub
public FootballClub(
int gPlayed, int gWins, int gLosses, int gDraws, int gFor, int gAgainst,
String inName, String inLocation, int inCapacity
) {
super(inName, inLocation, inCapacity);
played = gPlayed;
wins = gWins;
losses = gLosses;
draws = gDraws;
goalsFor = gFor;
goalsAgainst = gAgainst;
}
You should also make your member variables protected or private if you are using setters and getters.
I don't know how to print The object
You need to override toString. There is a short tutorial here.
Also unrelated side note: all Java variable identifiers should start with a lowercase letter.
When you have a method like this:
public void setName(String Name) { name = Name; }
It should be:
public void setName(String inName) { name = inName; }
Or:
public void setName(String name){ this.name = name; }

Subclasses and Superclasses

I'm trying to build a program that has certain requirements, the main being I have a class, and then make a subclass that adds a feature. I create the class DVD, and then I create the subclass.
I'm adding a method to add the year to the list, as well as a restocking fee which will be added to the final inventory value that prints. I built the subclass, created the overriding methods, but it is not being added to the output displayed. Not only that, but it is placing the input year in the wrong place. I am not getting any errors, it just acts like the subclass doesn't exist, even though my DVD class says that some of the methods are being overridden.
I'm thinking I must be missing something where I am supposed to call the new method, and maybe I read the resource wrong, but it sounded like I only needed to call the DVD class, and the methods I wanted overridden would be overridden automatically. I'd prefer to just add this information to the superclass, but it is a requirement for an assignment.
So I'm wondering how do I actually go about calling these override methods when I need them to add these new features? I keep seeing resources telling me how to create them, but not actually implement them.
From my main method, I call the dvd class and then print it. however, it only prints what's in the original dvd class, except for the odd addition of adding the year to where the product ID should be.
public class DVD {
String name;
int id;
int items;
double cost;
//default constructor
public DVD() {
name = "";
id = 0;
items = 0;
cost = 0.0;
}//end default constructor
//constructor to initialize object
public DVD(String dvdName, int itemNum, int quantity, double price) {
name = dvdName;
id = itemNum;
items = quantity;
cost = price;
}//end constructor
//method to calculate value
public double getInventoryValue() {
return items * cost;
}
//method to set name
public void setdvdName(String dvdName){
this.name = dvdName;
}
//method to get name
public String getName(){
return name;
}
//method to set id
public void setitemNum( int itemNum){
this.id = itemNum;
}
//method to get id
public int getId(){
return id;
}
//method to set items
public void setquantity(int quantity){
this.items = quantity;
}
//method to get items
public int getItems(){
return items;
}
//method to set cost
public void setprice( double price){
this.cost = price;
}
//method to get cost
public double getCost(){
return cost;
}
/**
*
* #return
*/
public String toString() {
return "DVD Name: " + getName() +
"ID: " + getId() +
"Items: " + getItems() +
"Cost: " + getCost() +
"Total Value: " +getInventoryValue();
}
}
-
public class ExtendedDVD extends DVD{
double restockFee;
int year;
public ExtendedDVD(){
year = 0;
}
public ExtendedDVD(int year) {
this.year = year;
}
public void setRestockFee(){
this.restockFee = 0.05;
}
public double getRestockFee(){
return restockFee;
}
public void setYear(){
this.year = 0;
}
public int getYear(){
return year;
}
#Override
public double getInventoryValue(){
double value1 = super.getInventoryValue();
double value = restockFee * value1;
double totalInventoryValue = value + super.getInventoryValue();
return totalInventoryValue;
}
#Override
public String toString(){
return super.toString() + "Year" + getYear();
}
}
}
public class Inventory {
DVD[] inventory = new DVD[5];
int current = 0;
private int len;
public Inventory(int len){
inventory = new DVD[len];
}
public double calculateTotalInventory() {
double totalValue = 0;
for ( int j = 0; j < inventory.length; j++ )
totalValue += inventory[j].getInventoryValue();
return totalValue;
}
/**
*
* #param dvd
* #throws Exception
*/
public void addDVD(DVD dvd) throws Exception {
if (current < inventory.length) {
inventory[current++]=dvd;
}else {
Exception myException = new Exception();
throw myException;
}
}
void sort() {
for (DVD inventory1 : inventory) {
len = current;
}
for (int i=0; i<len;i++) {
for(int j=i;j<len;j++) {
if (inventory[i].getName().compareTo(inventory[j].getName())>0) {
DVD temp = inventory[j];
inventory[j] = inventory[i];
inventory[i] = temp;
}
}
}
}
public int getNumberOfItems() {
return current;
}
public void printInventory() {
System.out.println("Current Inventory:");
for(int i=0;i<current;i++) {
System.out.println(inventory[i]);
}
System.out.println("The total value of the inventory is:"+calculateTotalInventory());
}
}
-
public class inventoryprogram1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
boolean finish = false;
String dvdName;
int itemNum;
int quantity;
double price;
int year = 0;
Inventory inventory = new Inventory(5);
while (!finish) {
Scanner input = new Scanner(System.in); // Initialize the scanner
System.out.print("Please enter name of DVD: ");
dvdName = input.nextLine();
if (dvdName.equals("stop")) {
System.out.println("Exiting Program");
break;
} else {
System.out.print("Please enter Product Number: ");
itemNum = input.nextInt();
System.out.print("Please enter units: ");
quantity = input.nextInt();
System.out.print("Please enter price of DVD: ");
price = input.nextDouble();
System.out.print("Please enter production year: ");
itemNum = input.nextInt();
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
try {
inventory.addDVD(dvd);
}catch( Exception e) {
System.out.println("Inventory is full.");
break;
}
System.out.println("DVD: " + dvd);
}//end else
}
inventory.sort();
inventory.printInventory();
}
}
if you want to use the new methods that you wrote in ExtendedDVD you need to instantiate that class you are still calling the original dvd class so you will still get those methods.
for example
DVD dvd = new DVD(dvdName, itemNum, quantity, price);
and
DVD Dvd = new ExtendedDVD(dvdName, itemNum, quantity, price);
are two different things
also if you look in your main method you are assigning itemNum twice that is why it is showing you the year
In the main method you just instantiate a DVD object, not an ExtendedDVD object.
replace
DVD dvd= new DVD(dvdName,itemNum,quantity,price);
by something like
DVD dvd= new ExtendedDVD(year);
And obviously, you may want another constructor in ExtendedDVD

Syntax and logic for moving player around game board array using do while loop java programming

I am trying to make a player move around a 2d board array in java while utilizing accessor and mutator methods to update the attributes of my object so I am going to try and make this question as in depth as possible. I do not understand the logic or the syntax that I must use to properly move the player and return the required information. I am working from code that was developed. My job is to move the player around the board and return information from a monopoly text file including the player position and new bank balance. Additionally, I have to ask if the player wants to continue and stop the game if the bank balance is zero. I really need help with the do while loop in the main method. I cannot get the syntax correct and do not have a great understanding of how the logic works. I am posting all of my code thus far.
package monopoly;
import java.util.*;
public class Monopoly {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
BoardSquare[] square = new BoardSquare[40]; // array of 40 monopoly squares
Player thePlayer = new Player();//new object thePlayer from Player class
thePlayer.getLocation();//call method getLocation which should be instantiated from player class to zero
int i;
loadArray(square);
Dice diceOne = new Dice();//new dice object
Dice diceTwo = new Dice();//new dice object
int rollOne; //variable to hold rollOne
int rollTwo; //variable to hold rollTwo
int rollTotal; //variable to hold rollTotal
do {
rollOne = diceOne.roll();
rollTwo = diceTwo.roll();
rollTotal = rollOne+rollTwo;
BoardSquare newPosition = square[thePlayer.getLocation() + rollTotal];
}
while (thePlayer.getBalance() > 0);
// test the code by printing the data for each square
System.out.println("Data from the array of Monopoly board squares. Each line has:\n");
System.out.println("name of the square, type, rent, price, color\n");
for(i = 0; i < 40; i++)
System.out.println( square[i].toString() );
}
//**************************************************************
// method to load the BoardSquare array from a data file
public static void loadArray(BoardSquare[] square) throws Exception {
int i; // a loop counter
// declare temporary variables to hold BoardSquare properties read from a file
String inName;
String inType;
int inPrice;
int inRent;
String inColor;
// Create a File class object linked to the name of the file to be read
java.io.File squareFile = new java.io.File("squares.txt");
// Create a Scanner named infile to read the input stream from the file
Scanner infile = new Scanner(squareFile);
/*
* This loop reads data into the square array.
* Each item of data is a separate line in the file.
* There are 40 sets of data for the 40 squares.
*/
for(i = 0; i < 40; i++) {
// read data from the file into temporary variables
// read Strings directly; parse integers
inName = infile.nextLine();
inType = infile.nextLine();
inPrice = Integer.parseInt( infile.nextLine() );
inRent = Integer.parseInt( infile.nextLine() );;
inColor = infile.nextLine();
// intialze each square with the BoardSquare constructor
square[i] = new BoardSquare(inName, inType, inPrice, inRent, inColor);
} // end for
infile.close();
} // endLoadArray
} // end class Monopoly
//**************************************************************
class BoardSquare {
private String name; // the name of the square
private String type; // property, railroad, utility, plain, tax, or toJail
private int price; // cost to buy the square; zero means not for sale
private int rent; // rent paid by a player who lands on the square
private String color; // many are null; this is not the Java Color class
// constructors
public BoardSquare() {
name = "";
type = "";
price = 0;
rent = 0;
color = "";
} // end Square()
public BoardSquare(String name, String type, int price, int rent, String color) {
this.name = name;
this.type = type;
this.price = price;
this.rent = rent;
this.color = color;
} // end Square((String name, String type, int price, int rent, String color)
// accesors for each property
public String getName() {
return name;
} //end getName()
public String getType() {
return type;
} //end getType()
public int getPrice() {
return price;
} //end getPrice()
public int getRent() {
return rent;
} //end getRent()
public String getColor() {
return color;
} //end getColor()
// a method to return the BoardSquare's data as a String
public String toString() {
String info;
info = (name +", "+type+", "+price + ", "+ rent+ ", "+color);
return info;
} //end toString()
} // end class BoardSquare
//**************************************************************
class Player {
private String name;
private String token;
private int location;
private int balance;
private String player;
public Player() {
name = "";
token = "";
location = 0;
balance = 1500;
} // end Square()
public Player(String name, String token, int location, int balance) {
this.name = name;
this.token = token;
this.location = location;
this.balance = balance;
}
/*
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the token
*/
public String getToken() {
return token;
}
/**
* #param token the token to set
*/
public void setToken(String token) {
this.token = token;
}
/**
* #return the location
*/
public int getLocation() {
return location;
}
/**
* #param location the location to set
*/
public void setLocation(int location) {
this.location = location;
}
/**
* #return the balance
*/
public int getBalance() {
return balance;
}
/**
* #param balance the balance to set
*/
public void setBalance(int balance) {
this.balance = balance;
}
/**
* #return the player
*/
public String getPlayer() {
return player;
}
/**
* #param player the player to set
*/
public void setPlayer(String player) {
this.player = player;
}
void setLocation() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
} //end class player
//**************************************************************
class Dice {
public static int roll() {
int total;
total = 1 + (int)(Math.random() * 6);
return total;
}
}
Start with writting down what should happen in the loop. I suggest some of the follwing:
print state of the board
throw dices and move player
perform action on new square (i.e ask player whether he wants to buy it or take the money if thesquare belongs to somebody else)
go too top, but now with the next player
You best write functions for all these steps. And as said, you'll probably want more than one player instance.
Edit:
Syntactically, you've almost got everything there already.
This prints the current state of the board, just copy it where you need it:
for( i=0; i<40; i++)
System.out.println( square[i].toString() );
The code in the loop moves the player:
rollOne=diceOne.roll();
rollTwo=diceTwo.roll();
rollTotal=rollOne+rollTwo;
BoardSquare newPosition=square[thePlayer.getLocation()+rollTotal];
Then the only step remaining is actually to perform the operation on the target square. This should probably best be a function of the player, so that would be:
player.ActionOnSquare(newPosition);
That requires a method in the player class:
public void OperationOnSquare(BoardSquare newSquare)
{
// Perform some operation, like reduce balance
}
Finally, you can ask the player whether he wants to continue. The mentioned steps 5 and 6 (you meant to write 6 and 7) are redundant, as that's already at the beginning of the next loop.

Why will objects now be created from my class

An error points to the word "new" when I try to compile this program. I'm trying to create 2 objects from the carOrder class and I'm havin troubles! I've had this problem with other programs before and I'm not sure why and it's killing me, please help!
import java.text.DecimalFormat;
import java.util.Scanner;
public class CarOrder
private String buyer;
private String carType;
private double cost;
private int quantity;
private boolean taxStatus;
private double discountedCost;
private double taxAmount;
// Default Constructor
public void carOrder()
{
}
// Constructor
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
buyer = buy;
carType = car;
cost = cos;
quantity = quan;
taxStatus = tax;
}
// Sets the company buying cars
public void setBuyer(String buy)
{
buyer = buy;
}
// Sets the car type being purchased
public void setCarType(String car)
{
carType = car;
}
// Sets cost of the cars being purchased
public void setCost(double cos)
{
cost = cos;
}
// Sets the quantity of cars being purchased
public void setQuantity(int quan)
{
quantity = quan;
}
// Sets tax status for the cars
public void setTaxStatus(boolean tax)
{
taxStatus = tax;
}
// Returns name of buyer to user
public String getBuyer()
{
return buyer;
}
// Returns type of car to user
public String getCarType()
{
return carType;
}
// Returns cost to user
public double getCost()
{
return cost;
}
// Returns quantity of cars to user
public int getQuantity()
{
return quantity;
}
// Returns tax status to user
public boolean getTaxStatus()
{
return taxStatus;
}
// Returns discounted cost to user
public double getDiscountedCost()
{
if (quantity > 10)
if (quantity > 20)
discountedCost = cost - cost * .10;
else
discountedCost = cost - cost * .05;
else
discountedCost = cost;
return discountedCost;
}
// Returns tax amount to users
public double getTaxAmount()
{
taxAmount = cost * .0625;
return taxAmount;
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter first Buyer");
String buyer1 = keyboard.nextLine();
}
}
public void CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
should be
public CarOrder(String buy, String car, double cos, int quan, boolean tax)
{
Constructor's don't have a return type, not even void.
Currently, you have a method named CarOrder in your class as it has a return type as void, which voilates the rules of custructor. If you remove void, then it'd a constructor as it has the same name as your class.
Same applies to your constructor with no-argsaswell.
public void CarOrder()
should be
public CarOrder()
you are missing a "{" right after public class CarOrder ... :)
When you don't declare a constructor, Java provides a default constructor that have no arguments. As you declared CarOrder(String buy, String car, double cos, int quan, boolean tax), the default constructor is not created anymore. You made a method called carOrder, that probably was an attempt to make a constructor with no arguments, but it has two problems:
it has a return type (void) and constructor doesn't have one
the name is different from the class (cardOrder isn't the same as CarOrder, since Java is case sensitive)
If you want to make a new CarOrder() call, just add the following code:
public CarOrder() {
//insert your implementation here
}
A constructor with a return type is treated as a method by the compiler.

Categories

Resources