sorry to be annoying, I am new to programming and am a bit confused.
How do I link variables of two classes? ie get a variable of one class into another? I'm trying to make an OOP scenario for a game platform where a player can join a game(max of 2 players per game, and pay an associated fee. I;'m trying to get a method which totals these in the Game class but I'm unsure how to add up all the players "amountOwed" into this. I also have to make sure both players are not the same player? any advice GREATLY appreciated! here is what i have so far
import java.time.LocalDate;
import java.time.Period;
import java.util.Date;
public class Player {
private static int instanceCounter = 0;
private int playerId;
private String playerName;
public int birthDay;
public int birthMonth;
public int birthYear;
public int playerAge;
public double amountOwed;
public Player(int playerId, String playerName, int birthDay, int birthMonth, int birthYear, double amountOwed) {
this.playerId = playerId;
this.playerName = playerName;
this.birthDay = birthDay;
this.birthMonth = birthMonth;
this.birthYear = birthYear;
this.amountOwed = amountOwed;
instanceCounter++;
}
public double getAmountOwed() {
return (amountOwed);
}
public int calculateAge() {
LocalDate birthDate = LocalDate.of(birthYear, birthMonth, birthDay);
LocalDate currentDate = LocalDate.now();
return playerAge = Period.between(birthDate, currentDate).getYears();
}
public String printDetails() {
return (playerName + ", with ID " + playerId + ", is " + playerAge + " and owes the game platform£" + amountOwed);
}
public String payFees() {
amountOwed = 0;
return ("Thank you" + playerName + ",you have paid for your game, your balance now stands at £0.00");
}
public String joinGameChess() {
if (instanceCounter < 3) {
return (playerName + " has joined the game.");
} else {
return ("Sorry, maximum of 2 players per game");
}
}
public String leaveGame() {
return (playerName + "has left the game.");
}
}
public class Game {
private String gameName;
private int gameId;
private int minAge;
private double fee;
public double amountOwed;
public double totalFeesOwed;
public Game(String gameName, int gameId, int minAge, double fee) {
this.gameId = gameId;
this.gameName = gameName;
this.minAge = minAge;
this.fee = fee;
}
public String printGameDetails() {
return (gameName + "of ID " + gameId + "has a minimum age of " + minAge + " and costs " + fee + " to play");
}
}
public class W07Practical {
public static void main(String[] args) {
Player marina = new Player(123, "Marina", 15, 4, 1999, 0);
marina.calculateAge();
System.out.println(marina.printDetails());
Game chess = new Game("chess", 1234, 19, 2);
marina.getAmountOwed();
System.out.println(marina.joinGameChess());
Player elise = new Player(153, "elise", 16, 3, 2000, 0);
System.out.println(elise.joinGameChess());
Player john = new Player(322, "john", 23, 5, 2002, 0);
System.out.println(john.joinGameChess());
System.out.println(john.printDetails());
System.out.println(elise.printDetails());
}
}
Total amount owed:
amountOwed = player1.getAmountOwed() + player2.getAmountOwed();
You can check both players are not same by their name or to be more precise by comparing their birthdays. For further precision compare both
Related
Based on the following UML class diagram I am trying to get the total population of all the House and ApartmentBuilding objects using an interface (Dwelling) and I am stuck on how to proceed. I have included the code I have so far.
Dwelling:
interface Dwelling {
int getNumberOfOccupants();
}
House:
import javafx.scene.canvas.GraphicsContext;
import java.util.Scanner;
public class House extends Building implements Dwelling {
private final int bedrooms;
private final int occupants;
private House(String name, double xPosition,int bedrooms, int occupants){
super(name,xPosition);
this.bedrooms = bedrooms;
this.occupants = occupants;
}
public static House create() {
Scanner scan = new Scanner(System.in);
House a;
System.out.println("Enter name of the House: ");
String name = scan.nextLine();
System.out.println("Enter XPosition of the House: ");
int xPosition = scan.nextInt();
System.out.println("Enter number of bedrooms: ");
int bedrooms = scan.nextInt();
System.out.println("Enter number of occupants: ");
int occupants = scan.nextInt();
a = new House(name, xPosition, bedrooms, occupants);
return a;
}
public void draw(GraphicsContext canvas){
}
#Override
public String toString(){
return "House: " + "bedrooms= " + bedrooms + " occupants= " + occupants + "\n" + super.toString();
}
#Override
public int getNumberOfOccupants() {
return occupants;
}
}
ApartmentBuilding:
import javafx.scene.canvas.GraphicsContext;
import java.util.Scanner;
public class ApartmentBuilding extends HighRise implements Dwelling{
private final int occupantsPerFloor;
private ApartmentBuilding(String name, double xPosition, int numberOfFloors, int occupantsPerFloor){
super(name, xPosition, numberOfFloors);
this.occupantsPerFloor = occupantsPerFloor;
}
public static ApartmentBuilding create() {
Scanner scan = new Scanner(System.in);
ApartmentBuilding a;
System.out.println("Enter name of the Apartment Building: ");
String name = scan.nextLine();
System.out.println("Enter XPosition of the Apartment Building: ");
int xPosition = scan.nextInt();
System.out.println("Enter number of floors: ");
int numberOfFloors = scan.nextInt();
System.out.println("Enter number of occupants per floor: ");
int occupantsPerFloor = scan.nextInt();
a = new ApartmentBuilding(name, xPosition, numberOfFloors, occupantsPerFloor);
return a;
}
public void draw(GraphicsContext canvas){
}
#Override
public String toString(){
return "Apartment Building: " + "occupantsPerFloor= " + occupantsPerFloor + "\n" + super.toString() + "\n";
}
#Override
public int getNumberOfOccupants() {
return numberOfFloors * occupantsPerFloor;
}
}
Building:
import javafx.scene.canvas.GraphicsContext;
public class Building implements Drawable {
private final String name;
private final double xPosition;
public Building(String name, double xPosition){
this.name = name;
this.xPosition = xPosition;
}
public String getName(){
return name;
}
public void draw(GraphicsContext canvas) {
}
public double getXPosition() {
return xPosition;
}
#Override
public String toString(){
return "Type... Building: " + "name= " + getName() + ", xPosition= " + getXPosition() + "\n";}
}
HighRise:
public class HighRise extends Building{
int numberOfFloors;
public HighRise(String name, double xPosition, int numberOfFloors) {
super(name, xPosition);
this.numberOfFloors=numberOfFloors;
}
public int getNumberOfFloors(){
return numberOfFloors;
}
#Override
public String toString() {
return "Type... HighRise: " + "numberOfFloors= " + getNumberOfFloors() + "\n" + super.toString();
}
}
Village:
import javafx.scene.canvas.GraphicsContext;
import java.util.Scanner;
public class Village extends Building{
private static String name;
private static int xPosition;
public static final double Y_FLOOR = 300;
private int size;
private final String villageName;
private final Building[] buildings;
private Village(String villageName, int size){
super(name, xPosition);
this.size = size;
this.villageName = villageName;
this.buildings = new Building[size];
}
public static Village create() {
Scanner scan = new Scanner(System.in);
Village a;
System.out.println("Enter name of village: ");
String villageName = scan.nextLine();
System.out.println("Enter number of buildings: ");
int num = scan.nextInt();
a = new Village(villageName, num);
for(int i = 0; i < num; i++) {
System.out.println("Enter type of Building: 1= House, 2= Apartment, 3= Store ");
int choice = scan.nextInt();
if (choice == 1){
a.buildings[i] = House.create();
}
if (choice == 2){
a.buildings[i] = ApartmentBuilding.create();
}
}
return a;
}
public int getPopulation(){
return size;
}
public void draw(GraphicsContext canvas){
}
public String toString(){
String str = "\n"+ "Village of " + villageName + "\n\n";
for (int i=0; i<buildings.length; i++) {
str = str + buildings[i].toString() + "\n"; // this adds each buildings information to the string
}
return str;
}
}
I am new at programming and trying my best to learn but I am getting stuck on this, unfortunately.
..I am trying to get the total population of all the House and ApartmentBuilding objects using an interface (Dwelling)..
You can not get the population while using that UML. Please try modify a bit as below.
First, Dwelling must declaire getPopulation();
Implementing getPopulation() within House and ApartmentBuilding
You need a variable to keep the population within House and ApartmentBuilding class as well (it will be returned while calling getPopulation()).
After that, you able to cast House and ApartmentBuilding to Dwelling. Then dwelling.getPopulation(). Hope it is useful.
The question wants me to do:
An array of Finance called financeRecord to store the details
of the payments for each semester.
This is my code
package lab5;
class Student_U extends Student {
public String student_name;
private String studentID;
public int student_age;
private byte currentSemester;
private byte TotalFinanceRecord;
private String cohort;
public Student_U() {
student_name = " ";
studentID = " ";
student_age = 0;
currentSemester = 1;
TotalFinanceRecord = 0;
cohort = " ";
}
public Student_U(String student_name, String studentID, int student_age,
String course, String year,
String section, String subject, String student_name2,
String studentID2, int student_age2,
byte currentSemester, byte totalFinanceRecord, String cohort) {
super(student_name, studentID, student_age, course, year,
section, subject);
student_name = student_name2;
studentID = studentID2;
student_age = student_age2;
this.currentSemester = currentSemester;
TotalFinanceRecord = totalFinanceRecord;
this.cohort = cohort;
}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public int getStudent_age() {
return student_age;
}
public void setStudent_age(int student_age) {
this.student_age = student_age;
}
public byte getCurrentSemester() {
return currentSemester;
}
public void setCurrentSemester(byte currentSemester) {
this.currentSemester = currentSemester;
}
public byte getTotalFinanceRecord() {
return TotalFinanceRecord;
}
public void setTotalFinanceRecord(byte totalFinanceRecord) {
TotalFinanceRecord = totalFinanceRecord;
}
public String getCohort() {
return cohort;
}
public void setCohort(String cohort) {
this.cohort = cohort;
}
public void initStudent() {
}
public void print() {
System.out.print("Student name: " + student_name + " ");
System.out.print("\nMatric No: " + studentID + " ");
System.out.print("\nAge: " + student_age + " ");
System.out.print("\nCurrent Semester: " + currentSemester + " ");
System.out.print("\nCohort: " + cohort + " ");
System.out.println();
}
}
Please help me fix my code I would appreciate it so much.
This is my lab assignment which needs to be submitted by tomorrow.
You could try this, but it's also better to review standard java concepts (arrays, classes, etc). After, just adapt your code as suitable.
public class Finance extends Student
{
public static void main(String args[])
{
Finance f1 = new Finance("Student_1");
System.out.println(f1);
f1.setPayment(1, 10);
System.out.println(f1);
f1.setPayment(2, 10.77);
System.out.println(f1);
Student s2 = new Student("Student 2");
Finance f2 = new Finance(s2);
f2.setPayment(2, 88.77);
System.out.println(f2);
}
Double finaceRecord[] = new Double[3];
private void initPayment()
{
for(int i=0;i<finaceRecord.length;i++)
{
finaceRecord[i]=0.0;
}
}
public Finance(Student s)
{
super(s.name);
initPayment();
}
public Finance(String name)
{
super(name);
initPayment();
}
//store first or second
public void setPayment(int i, double d)
{
if(d<=0) return;
if(i==1)
{
finaceRecord[i] = d;
}
else
{
finaceRecord[2] = d;
}
finaceRecord[0] = finaceRecord[2] + finaceRecord[1];
}
public String toString()
{
return "name="+super.name+", Total Paid="+finaceRecord[0]+","
+ " Sem1="+finaceRecord[1]+", Sem2="+finaceRecord[2];
}
}
...
public class Student
{
String name;
int Semester;
Student(String name)
{
this.name = name;
this.Semester = 1;
}
}
Ouptut
name=Student_1, Total Paid=0.0, Sem1=0.0, Sem2=0.0
name=Student_1, Total Paid=10.0, Sem1=10.0, Sem2=0.0
name=Student_1, Total Paid=20.77, Sem1=10.0, Sem2=10.77
name=Student 2, Total Paid=88.77, Sem1=0.0, Sem2=88.77
from what I understand you are supposed to create an array of Finance type
Finance []financeRecord = new Finance[totalFinanceRecord];
and then you can access the values of Finance class
financeRecord[indexNumber].methodName();
Truthfully, I mixed some codes.
I need output like below:
Parking ticket #:
Fined amount:
Car issued to:
Issued by officer:
But here is current output:
Fined amount:
Car issued to:
Parking ticket #:null
Fined amount:
Issued by officer:
So looks like the main issue is with generating a parking ticket #
Code is
import java.util.Scanner;
public class ParkingTicketSimulator
{
public static void main(String[] args)
{
String make, model, color, license, name, badge;
int parkedMinutes, meterMinutes;
Scanner keyboard = new Scanner(System.in);
System.out.print("=== Parking Ticket Simulator ===\n\n");
System.out.print("---------\n");
System.out.print("Car Data\n");
System.out.print("---------\n\n");
System.out.print("Enter the car make: ");
make = keyboard.nextLine();
System.out.print("Enter the car model: ");
model = keyboard.nextLine();
System.out.print("Enter the car color: ");
color = keyboard.nextLine();
System.out.print("Enter the car license number: ");
license = keyboard.nextLine();
System.out.print("Enter minutes car has been parked:");
parkedMinutes = keyboard.nextInt();
System.out.print("\n----------\n");
System.out.print("Meter Data\n");
System.out.print("----------\n\n");
System.out.print("Enter minutes purchased by driver:");
meterMinutes = keyboard.nextInt();
keyboard.nextLine();
System.out.print("\n-------\n");
System.out.print("PO Data\n");
System.out.print("-------\n\n");
System.out.println();
System.out.print("Enter police officer's name:");
name = keyboard.nextLine();
System.out.print("Enter police officer's badge number:");
badge = keyboard.nextLine();
System.out.print("\n---------------------\n");
System.out.print("Parking Ticket Issued\n");
System.out.print("---------------------\n\n");
ParkedCar car = new ParkedCar(make,model,color,license,parkedMinutes);
ParkingMeter meter1 = new ParkingMeter (meterMinutes);
PoliceOfficer officer1 = new PoliceOfficer(name,badge,car,meter1);
System.out.println(officer1.getExpired(officer1));
}
public static class ParkedCar {
private String make;
private String model;
private String color;
private String license;
private int minutesParked;
public ParkedCar() {
make = "";
model = "";
color = "";
license = "";
minutesParked = 0;
}
public ParkedCar(ParkedCar carDetails){
make = carDetails.make;
model = carDetails.model;
color = carDetails.color;
license = carDetails.license;
minutesParked = carDetails.minutesParked;
}
public ParkedCar(String make, String model, String color, String license, int minutesParked){
this.make = make;
this.model = model;
this.color = color;
this.license = license;
this.minutesParked = minutesParked;
}
public void setMake (String make){
this.make = make;
}
public void setModel (String model){
this.model = model;
}
public void setColor (String color){
this.color = color;
}
public void setLicense (String license){
this.license = license;
}
public void minutesParked (int minutesParked){
this.minutesParked = minutesParked;
}
public String getMake(){
return make;
}
public String getModel(){
return model;
}
public String getColor(){
return color;
}
public String getLicense(){
return license;
}
public int getMinutesParked(){
return minutesParked;
}
public String toString(){
String str = "\nMake: " + make + "\nModel: " + model + "\nColor: " + color + "\nLicense: " + license + "\nMinutes parked: " + minutesParked;
return str;
}
}
public static class ParkingMeter {
private int minutes;
public ParkingMeter() {
minutes = 0;
}
public ParkingMeter(int minutes){
this.minutes = minutes;
}
public ParkingMeter (ParkingMeter minutesDetail){
minutes = minutesDetail.minutes;
}
public void setMinutes (int minutes){
this.minutes = minutes;
}
public int getMinutes(){
return minutes;
}
public String toString(){
String str ="\nMinutes: " + minutes;
return str;
}
}
public static class ParkingTicket{
private PoliceOfficer officer; //Calls the officer details.
private ParkedCar car;
private ParkingMeter meter;
private int fees;
public ParkingTicket(PoliceOfficer officer){
this.officer = new PoliceOfficer(officer);
this.meter = officer.getMeter();
this.car = officer.getParkedCar();
}
public ParkingTicket(){
}
public int fees(){
int time;
if (car != null || meter != null){
time = car.getMinutesParked() - meter.getMinutes() - 1;
fees = 25;
while (time > 0){
time = time - 1;
fees = fees+10;
}
}
return fees;
}
public String toString(){
if (fees() == 0 ){
String str = "There is no ticket issued.";
return str;
}
else{
String str = "\n" + officer +"\nTime over: " + (car.getMinutesParked() - meter.getMinutes()) + "\nThe fee is $" + fees();
return str;
}
}
}
public static class PoliceOfficer{
private String name;
private String badge;
private ParkedCar car;
private ParkingMeter meter;
private ParkingTicket ticket;
public PoliceOfficer(String name, String badge, ParkedCar carDetails, ParkingMeter time) {
this.name = name;
this.badge = badge;
car = new ParkedCar(carDetails);
meter = new ParkingMeter(time);
}
public PoliceOfficer(PoliceOfficer officerDetails){
name = officerDetails.name;
badge = officerDetails.badge;
car = officerDetails.car;
meter = officerDetails.meter;
}
public void setName (String name){
this.name = name;
}
public void setBadge (String badge){
this.badge = badge;
}
public String getName(){
return name;
}
public String getBadge(){
return badge;
}
public ParkedCar getParkedCar() {
return new ParkedCar(car);
}
public ParkingMeter getMeter(){
return new ParkingMeter(meter);
}
public ParkingTicket getExpired(PoliceOfficer officer){
if (meter.getMinutes() - car.getMinutesParked() < 0){
ticket = new ParkingTicket(officer);
return ticket;
}
else
ticket = new ParkingTicket();
return ticket;
}
public String toString(){
String str = "Officer Details\nOfficer's Name: " + name + "\nOfficer's Badge Number: " + badge + "\n\nCar Information: " + car + "\n\nMeter Information: " + meter;
return str;
}
}
I'm new-ish to Java. I'm sorry this is so long. Directly below is the output of my code so far The part with ** is where I'm having a problem. I'm supposed to be comparing the speeds of two Car objects, but each Owner object is either a "safe" or "rash" driver. If they are rash, when they accelerate they speed up by 10. If they are safe, they speed up by 5. So far that aspect is working, however, only the first Owner object will store information. So whatever the first Owner object is (Safe/rash) they will both be. This isn't occurring for my Car objects, as each separate object is storing the correct information which is where I'm having difficulty. Can anyone help me figure out why?
Car Name: Betty
Year: 2002
Car Make: Kia
Car Model: Soul
Car Mileage: 50000
Car Speed: 65
Car owner name: Jane
Car owner type: rash
Car Name: Duke
Year: 2002
Car Make: Ford
Car Model: F250
Car Mileage: 50000
Car Speed: 65
Car owner name: John
Car owner type: safe
Betty is a 2002 Kia Soul.
The current mileage is 50000 and current speed is 65.
Jane is the owner of the car and is a rash driver.
Duke is a 2002 Ford F250.
The current mileage is 50000 and current speed is 65.
**Jane is the owner of the car and is a rash driver.**
The total mileage of both cars is 100000
Betty is going 75.
**Duke is going 75.**
This is what I have for class Car:
class Car{
//---INSTANCE VARIABLES---
private String carName;
private int yearModel;
private String make;
private String model;
private int speed;
private int mileage;
private Owner carOwner;
private static int totalMileage;
//---CAR CONSTRUCTOR---
public Car(String n, int y, String ma, String m, int ml, int s, Owner o) {
carName = n;
yearModel = y;
make = ma;
model = m;
speed = s;
mileage = ml;
carOwner = o;
totalMileage += ml;
}
//---MUTATOR & ACCESSOR METHODS---
public void setName(String n) {
carName = n;
}
public String getName() {
return carName;
}
public void setYearModel(int y) {
yearModel = y;
}
public int getYear() {
return yearModel;
}
public void setMake(String ma) {
make = ma;
}
public String getMake() {
return make;
}
public void setModel(String m) {
model = m;
}
public String getModel() {
return model;
}
public void setSpeed(int s) {
speed = s;
}
public int getSpeed() {
return speed;
}
public void setMileage(int ml) {
mileage = ml;
}
public int getMileage() {
return mileage;
}
public void setOwnerName(Owner n) {
carOwner = n;
}
public Owner getOwnerName() {
return carOwner;
}
//---ACCELERATE()---
public void accelerate() {
if(carOwner.getOwnType().equalsIgnoreCase("rash")) {
speed += 10;
} else {
speed += 5;
}
}
//---BRAKE---
public void brake() {
if(speed == 0) {
System.out.println("You are already stopped!");
} else {
speed -= 5;
}//end if-else statement
}
//---COMPARE()---
public void compare() {
}
//---TOSTRING()---
public String toString() {
String response = "";
response += "\n\n"+ carName +" is a " + yearModel + " " + make + " " + model+ ".";
response += "\nThe current mileage is " + mileage + " and current speed is " + speed;
response += ".\n" + carOwner.toString();
return response;
}
//---TOTALMILEAGE---
public static int getTotalMileage() {
return totalMileage;
}
}//---END CLASS CAR
class Owner:
public class Owner {
private String ownName;
private String ownType;
public Owner (String ownerName, String ownerType) {
ownName = ownerName;
ownType = ownerType;
}
public void setOwnType(String ownerType) {
ownType = ownerType;
}
public String getOwnType() {
return ownType;
}
public void setOwnName(String ownerName) {
ownName = ownerName;
}
public String getOwnName() {
return ownName;
}
public String toString() {
return ownName + " is the owner of the car and is a " + ownType + " driver.";
}
}//end Owner class
This is where my main method is:
import java.util.*;
public class carDemo {
public static void main(String[] args) {
Car car = null;
Owner owner = null;
Car car2 = null;
Owner owner2 = null;
String carName, make, model, ownerName, ownerType;
int yearModel, speed, mileage;
Scanner kb = new Scanner(System.in);
for(int i = 1; i <= 2; i++) {
System.out.print("Car Name: ");
carName = kb.nextLine();
System.out.print("Year: ");
yearModel = kb.nextInt();
kb.nextLine();
System.out.print("Car Make: ");
make = kb.nextLine();
System.out.print("Car Model: ");
model = kb.nextLine();
System.out.print("Car Mileage: ");
mileage = kb.nextInt();
kb.nextLine();
System.out.print("Car Speed: ");
speed = kb.nextInt();
kb.nextLine();
System.out.print("Car owner name: ");
ownerName = kb.nextLine();
System.out.print("Car owner type: ");
ownerType = kb.nextLine();
if(i == 2) {
owner2 = new Owner(ownerName, ownerType);
car2 = new Car(carName, yearModel, make, model, mileage, speed, owner);
} else {
owner = new Owner(ownerName, ownerType);
car = new Car(carName, yearModel, make, model, mileage, speed, owner);
}
} //end for loop
System.out.print(car);
System.out.print(car2);
System.out.println("\n\nThe total mileage of both cars is " + Car.getTotalMileage());
car.accelerate();
car2.accelerate();
System.out.println(car.getName() + " is going " + car.getSpeed() + ".");
System.out.println(car2.getName() + " is going " + car2.getSpeed() + ".");
} //end main
} //end carDemo
Both car and car2 gets the same owner instance in the constructor. One of them should be owner2.
car2 = new Car(carName, yearModel, make, model, mileage, speed, owner2);
// here ^
I started to develop my first java project, it's a kind of basic roleplaying game. I want to create a character.
First I'll explain a few things:
Game class - gets character class input (like Fighter).
Character - has all the character data.
CharacterClass - abstract class that includes information for each character class (like Fighter).
Fighter (and other classes) extends the abstract class CharacterClass, should set initial stats for the chosen character class (like Fighter).
What I want to do is choose a character class in Game (let's assume that I choose Fighter), and get all the stats by displayStats. When the character chooses a class then Game should call something like: Chracter ch = new Character(name, scan), and then ch.displayCharacter.
My problem is Fighter's constructor and assigning this data to Character's constructor.
public class Game {
public static void main(String[] args) {
System.out.println("Choose a character: ");
System.out.println("1. Fighter");
System.out.println("2. Rogue");
System.out.println("3. Mage");
System.out.println("4. Cleric");
Scanner sc = new Scanner(System.in);
int scan = sc.nextInt();
System.out.println("Character Class: " + CharacterUtil.getCharacterClass(scan));
System.out.println("Choose Name:");
Scanner nameIn = new Scanner(System.in);
String name = nameIn.next();
System.out.println("Name: " + name);
}
}
public class Character {
private String name;
private String characterClass;
private int level;
private int hp;
private int currentHp;
private long xp;
/*private int BAB; /*Base attack bonus*/
private int strength;
private int constitution;
private int dexterity;
private int intelligence;
private int wisdom;
private int charisma;
Character(String name, String chracterClass){
this.name = name;
this.characterClass = chracterClass;
level = ;
hp = ;
currentHp = hp;
xp = 0;
strength = ;
constitution = ;
dexterity = ;
intelligence = ;
wisdom = ;
charisma = ;
}
void displayCharacter(){
System.out.println("Name: " + name);
System.out.println("Level: " + level);
System.out.println("Class: " + characterClass);
System.out.println("HP: " + hp);
System.out.println("Attributes: ");
System.out.println("Strength: " + strength);
System.out.println("Constitution: " + constitution);
System.out.println("Dexterity: " + dexterity);
System.out.println("Intelligence: " + intelligence);
System.out.println("Wisdom: " + wisdom);
System.out.println("Charisma: " + strength);
System.out.println("XP: " + xp);
}
}
abstract class CharacterClass {
private int level;
private int hp;
private int strength;
private int constitution;
private int dexterity;
private int intelligence;
private int wisdom;
private int charisma;
CharacterClass(){
level = 1;
hp = 10;
strength = 10;
constitution = 10;
dexterity = 10;
intelligence = 10;
wisdom = 10;
charisma = 10;
}
class Fighter extends CharacterClass {
Fighter(){
super.level = 1;
super.hp = 10;
super.strength = 16;
super.constitution = 14;
super.dexterity = 14;
super.intelligence = 10;
super.wisdom= 10;
super.charisma = 10;
}
}
Either make your CharacterClass private fields protected instead of private so they can be accessed by subclasses or implement getters/setters in your abstract class and use them in your subclass constructor.
Also super.field does not mean anything : your are instanciating an object which will have the fields from the abstract class and the subclass, it will be this.fields that you want to access.
Sample code :
public abstract class CharacterClass {
private int intelligence;
private int strength;
private int dexterity;
private int vitality;
protected CharacterClass() {
setIntelligence(10);
setStrength(10);
setDexterity(10);
setVitality(10);
}
public int getDexterity() {
return dexterity;
}
protected void setDexterity(int dexterity) {
this.dexterity = dexterity;
}
public int getVitality() {
return vitality;
}
protected void setVitality(int vitality) {
this.vitality = vitality;
}
public int getStrength() {
return strength;
}
protected void setStrength(int strength) {
this.strength = strength;
}
public int getIntelligence() {
return intelligence;
}
protected void setIntelligence(int intelligence) {
this.intelligence = intelligence;
}
}
public class Fighter extends CharacterClass {
public Fighter() {
setStrength(15);
setVitality(15);
}
}
public class Main {
public static void main(String[] args) {
CharacterClass player = new Fighter();
System.out.println(player.getStrength());
System.out.println(player.getIntelligence());
}
}
This will print 15 followed by 10, because the strength has been modified by figther, but the intelligence is still the one defined in CharacterClass.
Note that you probably want your player to be more than a CharacterClass or a Figther. While you will have a lot of Figther, Rogues and Mages as PNJs, the player will have a whole other range of possibilities, like storing items in his inventory, interacting with the world, etc.
Good luck with your game !