Java adding from multiple classes with an interface - java

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.

Related

parking ticket sim having output issue

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;
}
}

The code is not outputting anything ever since I added the super keyword

Using the inheritance concept, I have common variables between the truck and car class such as no of cylinders and colour, on top of that, the truck class has a variable for towing capacity and the car class has a variable for number of seats. Therefore, I decided to use the keyword super to refer to the parent class but there seems to be no output.
import java.util.Scanner;
class Vehicle {
String color;
int noOfCylinders;
public Vehicle(String color, int noOfCylinders) {
this.color = "Black";
this.noOfCylinders = 0;
}
public void setColor(String c) {
color = c;
}
public String getColor() {
return color;
}
public void setNoOfCylinders(int noOfCyl) {
noOfCylinders = noOfCyl;
}
public int getNoOfCylinders() {
return noOfCylinders;
}
public String toString() {
String information;
information = "is " + color + " and it has " + noOfCylinders + " cylinders";
return information;
}
}
public class CreateVehicle {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Car CarObject = new Car(s.nextLine(), s.nextInt(), s.nextInt());
Truck TruckObject = new Truck(s.nextLine(), s.nextInt(), s.nextInt());
System.out.print("Enter the color of the car: ");
CarObject.setColor(s.nextLine());
System.out.print("Enter the number of cylinders in the car: ");
CarObject.setNoOfCylinders(s.nextInt());
System.out.print("Enter the number of seats in the car: ");
CarObject.setNoOfSeats(s.nextInt());
s.nextLine();
System.out.print("\nEnter the color of the truck: ");
TruckObject.setColor(s.nextLine());
System.out.print("Enter the number of cylinders in the truck: ");
TruckObject.setNoOfCylinders(s.nextInt());
System.out.print("Enter the towing capacity of the truck (lbs): ");
TruckObject.setTowingCapacity(s.nextInt());
System.out.print(("\nThe car ") + CarObject.toString() + ". ");
System.out.print(("\nThe truck ") + TruckObject.toString()+ ". ");
}
}
class Car extends Vehicle {
private int noOfSeats;
public Car(String color, int noOfCylinders, int seatNum) {
super(color, noOfCylinders);
this.noOfSeats = seatNum;
}
public void setNoOfSeats(int noOfSeat) {
noOfSeats = noOfSeat;
}
public String toString() {
System.out.print("The car has " + noOfSeats + " seats.");
return super.toString();
}
}
class Truck extends Vehicle {
private int towingCapacity;
public Truck(String color, int noOfCylinders, int capacityTowing) {
super(color, noOfCylinders);
this.towingCapacity = capacityTowing;
}
public void setTowingCapacity(int towingCapacityTruck) {
towingCapacity = towingCapacityTruck;
}
public String toString() {
System.out.print ("The truck has a towing capacity of " + towingCapacity + " lbs.");
return super.toString();
}
}
*
package problems;
import java.util.Scanner;
public class CreateVehicle {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Car CarObject = new Car(s.next(), s.nextInt(), s.nextInt());
Truck TruckObject = new Truck(s.next(), s.nextInt(), s.nextInt());
System.out.print("Enter the color of the car: ");
CarObject.setColor(s.next());
System.out.print("Enter the number of cylinders in the car: ");
CarObject.setNoOfCylinders(s.nextInt());
System.out.print("Enter the number of seats in the car: ");
CarObject.setNoOfSeats(s.nextInt());
s.nextLine();
System.out.print("\nEnter the color of the truck: ");
TruckObject.setColor(s.next());
System.out.print("Enter the number of cylinders in the truck: ");
TruckObject.setNoOfCylinders(s.nextInt());
System.out.print("Enter the towing capacity of the truck (lbs): ");
TruckObject.setTowingCapacity(s.nextInt());
System.out.print(("\nThe car ") + CarObject.toString() + ". ");
System.out.print(("\nThe truck ") + TruckObject.toString() + ". ");
}
}
class Truck extends Vehicle {
private int towingCapacity;
public Truck(String color, int noOfCylinders, int capacityTowing) {
super(color, noOfCylinders);
this.towingCapacity = capacityTowing;
}
public void setTowingCapacity(int towingCapacityTruck) {
towingCapacity = towingCapacityTruck;
}
public String toString() {
System.out.print ("The truck has a towing capacity of " + towingCapacity + " lbs.");
return super.toString();
}
}
class Car extends Vehicle {
private int noOfSeats;
public Car(String color, int noOfCylinders, int seatNum) {
super(color, noOfCylinders);
this.noOfSeats = seatNum;
}
public void setNoOfSeats(int noOfSeat) {
noOfSeats = noOfSeat;
}
public String toString() {
System.out.print("The car has " + noOfSeats + " seats.");
return super.toString();
}
}
class Vehicle {
String color;
int noOfCylinders;
public Vehicle(String color, int noOfCylinders) {
this.color = "Black";
this.noOfCylinders = 0;
}
public void setColor(String c) {
color = c;
}
public String getColor() {
return color;
}
public void setNoOfCylinders(int noOfCyl) {
noOfCylinders = noOfCyl;
}
public int getNoOfCylinders() {
return noOfCylinders;
}
public String toString() {
String information;
information = "is " + color + " and it has " + noOfCylinders + " cylinders";
return information;
}
}
I have just changed nextLine to next, assuming you are just expecting one word as input which is a color string. And it worked.

Displaying inputs using methods in java

I copied this code in a book I found in the internet about Data Structures and Algorithm in Java. This is the code:
//GameEntry Class
public class GameEntry
{
protected String name;
protected int score;
public GameEntry(String n, int s) {
name = n;
score = s;
}
public String getName() { return name; }
public int getScore() { return score; }
public String toString() {
return "(" + name + ", " + score + ")";
}
}
//Scores Class
public class Scores
{
public static final int maxEntries = 10;
protected int numEntries;
protected GameEntry[] entries;
public Scores(){
entries = new GameEntry[maxEntries];
numEntries = 3;
}
public String toString() {
String s = "[";
for(int i=0; i<numEntries; i++) {
if(i > 0) {
s = s + ", ";
}
s = s + entries[i];
}
return s + "]";
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scores s = new Scores();
for(int i=0; i<s.numEntries; i++){
System.out.print("Enter Name: ");
String nm = input.nextLine();
System.out.print("Enter Score: ");
int sc = input.nextInt();
input.nextLine();
s.entries[i] = new GameEntry(nm, sc);
System.out.println(s.toString());
}
}
}
This runs well like what it said in the book. It outputs:
//just an example input
[(John, 89), (Peter, 90), (Matthew, 90)]
What I don't understand is how did the names inside the parenthesis which is made in the GameEntry Class inside its toString() method (John, 89) is being outputted and yet what I written inside the System.out.println(s.toString); in Scores Class only pertains to the toString method in its own class?
I am expecting that the brackets in the toString() method in the Scores Class will be outputting only the brackets "[]" for it is the only one that I called in the main method... Can anyone please explain this to me how did this happened? I am little bit new in Java Data Structures.
Another thing I try to do this in a different sample program following the concept of what I see in the book..
This my codes:
//FirstClass
public class FirstClass
{
protected String name;
protected int age;
protected FirstClass(String n, int a) {
name = n;
age = a;
}
public String getName() { return name; }
public int getAge() { return age; }
public String printData() {
return "My name is: " + name + ", I am " + age + " years old";
}
}
//Second Class
import java.util.Scanner;
public class SecondClass
{
protected FirstClass f;
private static String nm;
private static int ag;
public SecondClass() {
f = new FirstClass(nm, ag);
}
public String toString(){
return "(" + f + ")";
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
SecondClass s = new SecondClass();
System.out.print("Enter Name: ");
nm = input.nextLine();
System.out.print("Enter Age: ");
ag = input.nextInt();
input.nextLine();
s.f = new FirstClass(nm, ag);
System.out.println(s.toString());
}
}
//Sample Input
Enter Name: John
Enter Age: 16
The output of this is:
(FirstClass#7cc7b1d2)
What I am expecting is:
("My name: is John, I am 16 years old")
What is my error in this???

How do I get a string user input and increase value by +1 using Java ArrayList?

I have the following code and I want to ask the user after an name that's already stored in the Arraylist and increase that (dogs) age by +1.
Here's the most important (I guess) part of the code. This is the Register Class.
import java.util.Scanner;
import java.util.ArrayList;
public class Register {
private Scanner keyboard = new Scanner(System.in);
private ArrayList<Dog> dogs = new ArrayList<>();
private String readString() {
return keyboard.nextLine();
}
public int readInt() {
int i = keyboard.nextInt();
keyboard.nextLine();
return i;
}
public double readDouble() {
double d = keyboard.nextDouble();
keyboard.nextLine();
return d;
}
public void registrateDog(){
System.out.println("Dogs name: ");
String name = readString();
System.out.println("Dogs breed: ");
String breed = readString();
System.out.println("Dogs age: ");
int age = readInt();
System.out.println("Dogs weight: ");
double weight = readDouble();
Dog newDog = new Dog(name, breed, age, weight);
dogs.add(newDog);
System.out.println(newDog.toString() + " is added");
}
public void increaseAge(){ //Here's the problem
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
private void exitProgram(){
System.out.println("Goodbye!");
keyboard.close();
}
private void run(){
setUp();
runCommandLoop();
exitProgram();
}
public static void main(String[] args){
new Register().run();
//setUp();
}
}
And
public class Dog {
private String name;
private String breed;
private int age;
private double weight;
private double tailLenght;
private String tax = "tax";
public Dog(String name, String breed, int age, double weight){
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
if (breed.equals(tax)) {
this.tailLenght = 3.7;
} else {
this.tailLenght = (age*weight) / 10;
}
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed(){
return breed;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public int newAge(){
return age = age + 1;
}
public double getWeight(){
return weight;
}
public double getTailLenght(){
return tailLenght;
}
public String toString()
{ return String.format("%s, %s, %d years old, %.1f kg, "
+ "tail lenght %.1f cm", name, breed, age, weight, tailLenght);
}
}
So in this code you're finding the Dog by its name. Which is great.
public void increaseAge() {
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
Inside of your Dog class you have a method which returns the age, what you want to do is modify it to:
public int newAge(){
this.age++; // This will take the current age of the dog and add one to it
}
Now going back to the increaseAge() method you want to modify the for loop to look like:
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
dogs.get(i).newAge(); // This will update the Dogs age by 1 year
System.out.println("Dog " + dogs.get(i).getName() + " is now " + dogs.get(i).getAge());
return;
}
Where are you incrementing the age ? Call the newAge() method as you have defined in the Dog class.`
Dog dog = dogs.get(i);
dog.setAge(dog.newAge());
dogs.set(i,dog);`
We've fetched the particular dog who's details matched. Then we incremented it's age and set it back in the list at that position.

Java constructor of a subclass of an abstract class

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 !

Categories

Resources