This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm new to Java and trying to compile this inventory program. I keep getting the same error message and can't figure out what I'm missing. The error is cannot find symbol and it is on lines 10,18,20,21,22,23 anyting that says Inventory has the ^ symbol pointing at them. I am enclosing what I have racked my brains and tried everything I can and would appreciate any help with this.
//InventoryProgram2.java
//Camera inventory program
import java.util.Arrays;
public class InventoryProgram2
{
public static void main( String args [])
{
//instantiate camera object
Inventory myInventory = new Inventory();
//displays welcome message
System.out.println( "Camera Invenotry Program");
System.out.println();//skips a line
//create and initialize an array of Cameras
Inventory[] Camera = new Inventory[4];
Camera[0] = new Inventory( 1980, "Cannon Rebel T3", 20, 489.99);
Camera[1] = new Inventory( 2120, "Nikon CoolPix L810", 5, 279.99);
Camera[2] = new Inventory( 1675, "Sony CyberShot HX200V", 12, 479.99);
Camera[3] = new Inventory( 1028, "Fujifilm FinePix S4300", 3, 199.99);
//for each array element, output value
for(int count = 0; count < Camera.length; count++)
{
Camera[count] = count+1;
System.out.printf("Product Number: %4.2f\n", Camera[count].getprodNumber() );
System.out.printf("Product Name: %s\n", Camera[count].getprodName() );
System.out.printf("Units In Stock: %.2f\n", Camera[count].getunitsTotal() );
System.out.printf("Unit Price: $%4.2f\n", Camera[count].getunitPrice() );
System.out.printf("Inventory Value: $%4.2f\n", Camera[0].gettotalInventory() );
System.out.println();//blank line to seperate products
}//end for
}//end main method
}//end public class InventoryProgram2
class Camera
{
private int prodNumber;//product number
private String prodName;//product name
private int unitsTotal;//total units in stock
private double unitPrice;//price per unit
private double totalInventory;//amount of total inventory
//initializa four-argument constructor
public Camera ( int number, String name, int total, double price)
{
prodNumber = number;
prodName = name;
setUnitsTotal (total);//validate and store total of camera
setUnitPrice (price);//validate and store price per camera
}//end four-argument constructor
public void setProdNumber (int number)
{
prodNumber = number;
}
public int getProdNumber()
{
return prodNumber;
}
public void setProdName (String name)
{
prodName = name;
}
public String getProdName()
{
return prodName;
}
public void setUnitsTotal (int total)
{
unitsTotal = total;
}
public int getUnitsTotal()
{
return unitsTotal;
}
public void setUnitPrice (double price)
{
unitPrice = price;
}
public double getUnitPrice()
{
return unitPrice;
}
// method to set Inventory value
//public void setInventoryValue(double value)
//{
//InventoryValue = value;
//}end method setInventoryValue
//method to get InventoryValue
//public double getInventoryValue()
//{
// return InventoryValue;
//} //end method to getInventoryValue
public double getInventoryValue()
{
return unitPrice * unitsTotal;
}//end method to getInventoryValue
//method to set TotalInventory
//public void setTotalInventory(double value)
//{
//TotalInventory = total;
//}end method setTotalInventory
//method to get TotalInventory
//public double getTotalInventory()
//{
//return TotalInventory;
//}end method to getTotalInventory
}//end class Camera
I needed to keep one class camera so I did some adjustemnts. I'm down to 7 errors as follows:
line 10: error: constructor Camera in class Camera cannot be applied to given types;
Camera myCamera = new Camera();
required: int,String,int,double
found: no arguments
reason: actual and formal argument lists differ in length
line 29: error: incompatible types
Inventory[count] = count+1
^
required: Camera
found: int
lines 31, 32, 33, 34, 35, : error cannot find symbol
System.out.printf(......) [count].getprodNumber
^
symbol: method getprodNumber()
location: class Camera
here is my updated code:
//Inventory.java
//Camera inventory program
import java.util.Arrays;
public class Inventory
{
public static void main( String args [])
{
//instantiate camera object
Camera myCamera = new Camera();
//displays welcome message
System.out.println( "Camera Invenotry Program");
System.out.println();//skips a line
//create and initialize an array of Cameras
Camera[] Inventory = new Camera[4];
Inventory[0] = new Camera( 1980, "Cannon Rebel T3", 20, 489.99);
Inventory[1] = new Camera( 2120, "Nikon CoolPix L810", 5, 279.99);
Inventory[2] = new Camera( 1675, "Sony CyberShot HX200V", 12, 479.99);
Inventory[3] = new Camera( 1028, "Fujifilm FinePix S4300", 3, 199.99);
//for each array element, output value
for(int count = 0; count < Inventory.length; count++)
{
Inventory[count] = count+1;
System.out.printf("Product Number: %4.2f\n", Inventory[count] .getprodNumber() );
System.out.printf("Product Name: %s\n", Inventory[count] .getprodName() );
System.out.printf("Units In Stock: %.2f\n", Inventory[count] .getunitsTotal() );
System.out.printf("Unit Price: $%4.2f\n", Inventory[count] .getunitPrice() );
System.out.printf("Inventory Value: $%4.2f\n", Inventory[0] .gettotalInventory() );
System.out.println();//blank line to seperate products
}//end for
}//end main method
}//end public class Inventory
class Camera
{
private int prodNumber;//product number
private String prodName;//product name
private int unitsTotal;//total units in stock
private double unitPrice;//price per unit
private double totalInventory;//amount of total inventory
//initializa four-argument constructor
public Camera ( int number, String name, int total, double price)
{
prodNumber = number;
prodName = name;
setUnitsTotal (total);//validate and store total of camera
setUnitPrice (price);//validate and store price per camera
}//end four-argument constructor
public void setProdNumber (int number)
{
prodNumber = number;
}
public int getProdNumber()
{
return prodNumber;
}
public void setProdName (String name)
{
prodName = name;
}
public String getProdName()
{
return prodName;
}
public void setUnitsTotal (int total)
{
unitsTotal = total;
}
public int getUnitsTotal()
{
return unitsTotal;
}
public void setUnitPrice (double price)
{
unitPrice = price;
}
public double getUnitPrice()
{
return unitPrice;
}
// method to set Inventory value
//public void setInventoryValue(double value)
//{
//InventoryValue = value;
//}end method setInventoryValue
//method to get InventoryValue
//public double getInventoryValue()
//{
// return InventoryValue;
//} //end method to getInventoryValue
public double getInventoryValue()
{
return unitPrice * unitsTotal;
}//end method to getInventoryValue
//method to set TotalInventory
//public void setTotalInventory(double value)
//{
//TotalInventory = total;
//}end method setTotalInventory
//method to get TotalInventory
//public double getTotalInventory()
//{
//return TotalInventory;
//}end method to getTotalInventory
}//end class Camera
It looks like your Camera class should really be called Inventory. You're using Camera in your main application class as a variable name not as a type.
Change class Camera to class Inventory
and
public Camera ( int number, String name, int total, double price)
to
public Inventory ( int number, String name, int total, double price)
and it should get you closer, if not all the way there.
Check if Inventory class is in the same package as that of this class. Else just import that class like you did for Arrays.
Related
Everytime I run my code, I get this error below
Exception in thread "main" java.lang.NoSuchMethodError: 'void Car.<init>(java.lang.String, java.lang.String, double, double, double)'
at DimaweaJeshuaAssignment11.setUpCars(DimaweaJeshuaAssignment11.java:48)
at DimaweaJeshuaAssignment11.main(DimaweaJeshuaAssignment11.java:11)
I looked to see if my constructor in my Car class was correct, and it was, but I'm stuck and can't figure out what the problem is. This is my code below
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class DimaweaJeshuaAssignment11 {
public static void main(String[] args) throws IOException {
// create an array of 5 Car objects
Car[] cars = new Car[5];
// set up the cars
setUpCars(cars);
// output the car details to file
writeCarDetailsToFile(cars);
// display the cars at the start of simulation
System.out.println("Cars at start of simulation");
printCars(cars);
int milesTraveled = 0;
boolean allCarsHaveGas = true;
// loop that continues until at least one of the cars has run out of gas
while(allCarsHaveGas) {
milesTraveled++; // increment the miles traveled
// loop to decrement the gallons after traveling 1 mile
for(int i=0;i<cars.length;i++) {
cars[i].updateFuel(1);
if(cars[i].getFuelGauge().getGallons() == 0) { // check if any of cars have run out of gas, update allCarsHaveGas to false
allCarsHaveGas = false;
}
}
}
// display the car details at the end of simulation
System.out.println("Cars at end of simulation");
printCars(cars);
// loop to display the first car that ran out of gas
for(int i = 0; i < cars.length; i++) {
if(cars[i].getFuelGauge().getGallons() == 0) {
System.out.println("\n"+cars[i].getOwner()+"'s car ran out of has after "+ milesTraveled +" miles");
break;
}
}
}
// method to set up the cars for the simulation based on the given information
public static void setUpCars(Car[] cars) {
cars[0] = new Car("Shrek", "Toyota Tundra", 15, 6, 20000);
cars[1] = new Car("Fiona", "Audi Q7", 21, 10, 8270);
cars[2] = new Car("Donkey", "Jeep CJ5", 14, 5, 11800);
cars[3] = new Car("Farquaad", "Smart Car", 42, 4, 710);
cars[4] = new Car("Dragon", "Chevy Suburban", 12, 30, 10800);
}
// method to display the details of the car in the array
public static void printCars(Car[] cars) {
System.out.println("----------------------------------------------------------------------------------------");
System.out.printf("%-20s%-20s%20s%20s\n","Owner","Brand","MPG","Current Gallons", "Mileage");
System.out.println("----------------------------------------------------------------------------------------");
for(int i=0;i<cars.length;i++)
System.out.printf("%-20s%-20s%20.2f%20.2f\n",cars[i].getOwner(),cars[i].getBrand(),cars[i].getFuelEconomy(),cars[i].getFuelGauge().getGallons(), cars[i].getMileage());
System.out.println();
}
// method to display the details of cars in the array to file
public static void writeCarDetailsToFile(Car[] cars) throws IOException {
// setup the file reference variable to refer to the text file
File filename = new File("Assignment11.txt");
// Create the file that the cars will be written to
PrintWriter resultsFile = new PrintWriter(filename);
// Write the details for each car to the file
for(int i=0;i<cars.length;i++) {
resultsFile.println(cars[i].getOwner());
resultsFile.println(cars[i].getBrand());
resultsFile.println(cars[i].getFuelEconomy());
resultsFile.println(cars[i].getFuelGauge().getGallons());
}
resultsFile.close();
}
}
class Car {
// attributes
private String owner;
private String brand;
private double milesPerGallon;
private FuelGauge fuelGauge;
private double mileage;
// constructor to initialize fields to specified values
public Car(String owner, String brand, double milesPerGallon, double gallons, double mileage) {
this.owner = owner;
this.brand = brand;
this.milesPerGallon = milesPerGallon;
fuelGauge = new FuelGauge();
fuelGauge.setGallons(gallons);
this.mileage = mileage;
}
// getters
public String getOwner() {
return owner;
}
public String getBrand() {
return brand;
}
public double getFuelEconomy() {
return milesPerGallon;
}
public FuelGauge getFuelGauge() {
return fuelGauge;
}
public double getMileage() {
return mileage;
}
// update the fuel of the car based on the miles traveled
public void updateFuel(double milesTraveled) {
double gallonsUsed = milesTraveled/milesPerGallon; // compute the gallons used for traveling milesTraveled
fuelGauge.decrementGallons(gallonsUsed); // decrement the gallons used
}
}
class FuelGauge {
// attribute
private double gallons;
// default constructor that initialize gallons to 0
public FuelGauge() {
}
// setter
public void setGallons(double gallons) {
this.gallons = gallons;
}
// getter
public double getGallons() {
return gallons;
}
// method to decrement the gallons by gallons used
public void decrementGallons(double gallonsUsed) {
if(gallonsUsed <= gallons) { // gallonsUsed <= gallons, decrement gallonsUsed from gallons
gallons -= gallonsUsed;
} else // gallonsUsed > gallons, set gallons to 0
gallons = 0;
}
}
Okay so working on my first assignment for my introduction to Java class. I have read the first 2 chapters in the book probably 6 times now and I've looked at a dozen various tutorials online and I'm still not getting what the problem is here.
I have class Student
//declare main class
public class Student {
// declare variables needed including ID_number, Credit_hours, points and GPA
private float ID_number;
private int Credit_hours;
private int points;
public float GPA;
// methods will go here
//method to return ID number
public float getID_number()
{
return ID_number;
}
//method to set the ID number
public void setID_number(float ID_number)
{
ID_number = ID_number;
}
//method to return credit hours
public int getCredit_hours()
{
return Credit_hours;
}
//method to set credit hours
public void setCredit_hours(int Creds)
{
Credit_hours = Creds;
}
//method to get points
public int getpoints()
{
return points;
}
//method to set points
public void setpoints(int points)
{
points = points;
}
//method to calculate and return GPA
public float setGPA()
{
GPA = points/Credit_hours;
//return GPA;
}
//method to print the GPA
public float getGPA(float GPA)
{
return GPA;
}
}
and then I have the class ShowStudent which is supposed to instantiate the Student Class:
import java.util.Scanner;
class ShowStudent
{
public static void main (String args[])
{
Student newStudent;
newStudent = getStudentInfo();
displayStudent(newStudent);
}
public static Student getStudentInfo()
{
Student tempStu = new Student();
float ID_number;
int Credit_hours;
int points;
Scanner input = new Scanner(System.in);
System.out.print("Enter Student ID Number >> ");
ID_number = input.nextFloat();
tempStu.setID_number(ID_number);
}
public static void displayStudent(Student aStu)
{
System.out.println("\nStudnet number is: #" + aStu.getID_number() +
" While their GPA is " + aStu.getGPA());
}
}
but eclipse is throwing all kinds of errors at me including the following:
"method must return type student" line 12 in showStudent
"Method getGPA is not applicable for this argument" Line 28 in showStudent
I just do not understand what is the problem here and I'm getting super frustrated with this.
Firsly you getStudentInfo() must return a Student object like this
public static Student getStudentInfo()
{
Student tempStu = new Student();
float ID_number;
int Credit_hours;
int points;
Scanner input = new Scanner(System.in);
System.out.print("Enter Student ID Number >> ");
ID_number = input.nextFloat();
tempStu.setID_number(ID_number);
return tempStu;
}
And secondly, you miseed up your getters and setters and some variable implementations in your student class. It should be like this
public class Student {
// declare variables needed including ID_number, Credit_hours, points and GPA
private float ID_number;
private int Credit_hours;
private int points;
public float GPA;
// methods will go here
//method to return ID number
public float getID_number()
{
return ID_number;
}
//method to set the ID number
public void setID_number(float ID_number)
{
this.ID_number = ID_number;
}
//method to return credit hours
public int getCredit_hours()
{
return Credit_hours;
}
//method to set credit hours
public void setCredit_hours(int Creds)
{
Credit_hours = Creds;
}
//method to get points
public int getpoints()
{
return points;
}
//method to set points
public void setpoints(int points)
{
this.points = points;
}
//method to calculate and return GPA
public float getGPA()
{
return GPA;
}
//method to print the GPA
public void setGPA(float GPA)
{
this.GPA = GPA;
}
}
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
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.
hello I get the error message: Missing Method Body Or Declare Abstract, how to fix this, what does this mean?
my code:
public class Mobile
{
// type of phone
private String phonetype;
// size of screen in inches
private int screensize;
// memory card capacity
private int memorycardcapacity;
// name of present service provider
private String mobileServiceProvider;
// type of contract with service provider
private int mobileTypeOfContract;
// camera resolution in megapixels
private int cameraresolution;
// the percentage of charge left on the phone
private int chargeUp;
// wether the phone has GPS or not
private int switchedOnFor;
// to simulate using phone for a period of time
private int charge;
// checks the phones remaining charge
private String provider;
// simulates changing the provider
private String GPS;
// instance variables - replace the example below with your own
private int cost;
// declares cost of the item
// The constructor method
public Mobile(String mobilephonetype, int mobilescreensize,
int mobilememorycardcapacity, String mobileServiceProvider, int mobileTypeOfContract, int mobilecameraresolution, String mobileGPS, int chargeUp,int switchedOnFor, String changeProvider,int getBalance, int cost,int price) {
// initialise the class attributes from the one given as parameters in your constructor.
}
/**
* Other constructor
*/
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
/**
*returns a field price.
*/
public int getcost()
{
return balance;
}
/**
*return the amount of change due for orders of mobiles.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money from a customer.
*/
public void cost (int price)
{
balance = balance + amount;
}
//this.serviceprovider = newserviceprovider;
//this.typeofcontract = 12;
//this.checkcharge = checkcharge;
//this.changeProvider = giffgaff;
//Mobile samsungPhone = new Mobile(
// "Samsung" // String mobilephonetype
//, 1024 // intmobilescreensize
//, 2 // intmobilememorycardcapacity
//, 8 // intmobilecameraresolution
//, "GPS" //String mobileGPS
//, "verizon" // String newserviceprovider
//, "100" // intchargeUp
//, "25" // intswitchedOnFor
//, "25" // intcheckCharge
//, "giffgaff"// String changeProvider
//);
//typeofcontract = 12;
//checkcharge = checkcharge;
//Mutator for newserviceprovider
public void setmobileServiceProvider(String newmobileServiceProvider)
{
mobileServiceProvider = newmobileServiceProvider;
}
//Mutator for contracttype
public void setmobileTypeOfContract(int newmobileTypeOfContract)
{
mobileTypeOfContract = newmobileTypeOfContract;
}
//Mutator for chargeUp
public void setchargeUp(int chargeUp)
{
this.chargeUp = chargeUp;
}
//Mutator to simulate using phone for a period of time
public void switchedOnFor(int switchedOnFor)
{
this.switchedOnFor = switchedOnFor;
}
//Accessor for type of phone
public String getType()
{
return phonetype;
}
//Accessor for provider
public String getprovider()
{
return mobileServiceProvider;
}
//Accessor for contract type
public int getContractType()
{
return mobileTypeOfContract;
}
//Accessor for charge
public int getCharge()
{
return chargeUp;
}
//Accessor which checks the phones remaining charge
public int checkCharge()
{
return checkCharge;
}
// simulates changing the provider
public void changeProvider()
{
provider = changeProvider;
}
//returns the amount of change due for orders of mobiles.
public int Balance()
{
return balance;
}
// A method to display the state of the object to the screen
public void displayMobileDetails() {
System.out.println("phonetype: " + phonetype);
System.out.println("screensize: " + screensize);
System.out.println("memorycardcapacity: " + memorycardcapacity);
System.out.println("cameraresolution: " + cameraresolution);
System.out.println("GPS: " + GPS);
System.out.println("mobileServiceProvider: " + mobileServiceProvider);
System.out.println("mobileTypeOfContract: " + mobileTypeOfContract );
}
/**
* The mymobile class implements an application that
* simply displays "new Mobile!" to the standard output.
*/
public class mymobile {
public void main(String[] args) {
System.out.println("new Mobile!"); //Display the string.
}
}
public static void buildPhones(){
Mobile Samsung = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
Mobile Blackberry = new Mobile("Samsung",3,4,"verizon",8,12,"GPS",100,25,"giffgaff");
}
public static void main(String[] args) {
buildPhones();
}
}
any answers or replies and help would be greatly appreciated as I cant get it to compile like it did before with no syntax errors.
Check constructor declared on line 42. It doesn't have a body.
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Additionally, price and a number of other fields are not declared anywhere.
remove ; from
public Mobile (int cost); {
public Mobile (int cost); {
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}
Here, you left a semicolon, delete it.
public Mobile (int cost){
price = 1000;
// initialise cost(?) attribute that actually doesn't seem to exist?
}