I am just in learning phase & here I am using some polymorphism technique. This is the code:
package com.company;
class Car{
private String name;
private int cylinder;
private boolean engine;
private int wheels;
public Car(String name, int cylinder) {
this.name = name;
this.cylinder = cylinder;
this.engine = true;
this.wheels = 4;
}
public String startEngine(int fuel){
if(fuel>0){
return "Start button pressed";
} else{
return "First fill some fuel";
}
}
public String accelerate(int speed){
return "Car is accelerated with speed " + speed;
}
public String brake(int speed){
return "Brake is presses. Now speed is " + speed;
}
public String getName() {
return name;
}
public int getCylinder() {
return cylinder;
}
}
class Fortuner extends Car{
public Fortuner() {
super("Fortuner", 4);
}
#Override
public String accelerate(int speed) {
return "Fortuner is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Fortuner is moving with " + speed + " kph";
}
}
class Hondacity extends Car{
public Hondacity() {
super("Hinda City", 6);
}
#Override
public String accelerate(int speed) {
return "Honda City is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Honda City is moving with " + speed + " kph";
}
}
class Omni extends Car{
public Omni() {
super("Omni", 1);
}
#Override
public String accelerate(int speed) {
return "Omni is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Omni is moving with " + speed + " kph";
}
}
public class Main {
public static void main(String[] args) {
for(int j=0; j<3; j++){
Car car = speedup();
System.out.println(car.accelerate(50));
}
}
public static Car speedup() {
for(int i=0; i<3; i++){
switch(i){
case 0: return new Fortuner();
case 1: return new Hondacity();
case 2: return new Omni();
}
}
return null;
}
}
When I run it, it's giving output like this:
Fortuner is accelerated with speed 50 Fortuner is accelerated with
speed 50 Fortuner is accelerated with speed 50
But I want to give output something like this
Fortuner is accelerated with speed 50 Hondacity is accelerated with
speed 50 Omni is accelerated with speed 50
I know this is happening due to initialization each time when method runs. How can I solve it? Please apologize me for poor algorithm as I am just a learner.
Your method speedup() always returns a Fortuner, as it never gets any further. The return command always exits the loop. So if you want to get all the classes, you would have to do it like this:
public static void main(String[] args) {
for(int ID=0; ID<3; ID++){
Car car = speedup(ID);
System.out.println(car.accelerate(50));
}
}
public static Car speedup(int ID) {
switch(i){
case 0: return new Fortuner();
case 1: return new Hondacity();
case 2: return new Omni();
}
return null;
}
In your method speedup() the value of j each time is 0. so it always return Fortuner. I have removed this method to solve it.
class Car {
private String name;
private int cylinder;
private boolean engine;
private int wheels;
public Car(String name, int cylinder) {
this.name = name;
this.cylinder = cylinder;
this.engine = true;
this.wheels = 4;
}
public Car() {
}
public String startEngine(int fuel){
if(fuel>0){
return "Start button pressed";
} else{
return "First fill some fuel";
}
}
public String accelerate(int speed){
return "Car is accelerated with speed " + speed;
}
public String brake(int speed){
return "Brake is presses. Now speed is " + speed;
}
public String getName() {
return name;
}
public int getCylinder() {
return cylinder;
}
}
class Fortuner extends Car{
public Fortuner() {
super("Fortuner", 4);
}
#Override
public String accelerate(int speed) {
return "Fortuner is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Fortuner is moving with " + speed + " kph";
}
}
class Hondacity extends Car{
public Hondacity() {
super("Hinda City", 6);
}
#Override
public String accelerate(int speed) {
return "Honda City is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Honda City is moving with " + speed + " kph";
}
}
class Omni extends Car{
public Omni() {
super("Omni", 1);
}
#Override
public String accelerate(int speed) {
return "Omni is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Omni is moving with " + speed + " kph";
}
}
public class Main {
public static void main(String[] args) {
for(int j=0; j<3; j++){
Car car = null;
switch (j) {
case 0: car = new Fortuner();
break;
case 1: car = new Hondacity();
break;
case 2: car = new Omni();
break;
}
System.out.println(car.accelerate(50));
}
}
}
Related
Initially, my piece of code looked like this :
public interface Picture {
public String toString();
}
class PolyLine extends Line implements Picture{
int numSides =0;
Line sideLengths[];
public PolyLine(Line[] l1) {
super(l1);
sideLengths = l1;
numSides = l1.length;
}
#Override
public String toString() {
return " "+"number of sides "+ numSides + " "+ "coordinates of the beginning and end of the lines that make up the polygon\n"+ Arrays.toString(sideLengths) + " " ;
}
}
And everything worked great.But since I can implement the String toString method without using the interface, it's a bit useless, but I have such a task.So I decided to make the method in the interface a little different.But everything stopped working. That is, information has stopped being output to the console.But I can't figure out why.Again, this is my task to do this way. I know I can use the first version, but I'd like to know why the second one doesn't work.
public interface Picture {
public void Draw();
}
class PolyLine extends Line implements Picture{
int numSides =0;
Line sideLengths[];
public PolyLine(Line[] l1) {
super(l1);
sideLengths = l1;
numSides = l1.length;
}
#Override
public void Draw() {
System.out.println(" "+"number of sides "+ numSides + " "+ "coordinates of the beginning and end of the lines that make up the polygon\n"+ Arrays.toString(sideLengths) + " " ) ;
}
}
full code:
import java.util.Arrays;
abstract class Point {
Double x;
Double y;
public Point(double x, double y) {
this.setX(x);
this.setY(y);
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public Point() {
x=0.0;
y=0.0;
}
public String toString() {
return x + " " + y + "\n";
}
}
class ColoredPoint extends Point{
public Color color;
public ColoredPoint (double x, double y,Color color) {
super(x,y);
this.color=color;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public ColoredPoint () {
x=0.0;
y=0.0;
color=Color.getRandomColor();
}
#Override
public String toString() {
return"("+ x + " " + y +") "+ " " + color + "\n";
}
}
class Line extends Point{
public Point start;
public Point end;
public Line(Point p1, Point p2) {
start = p1;
end = p2;
}
public Line(Line[] l1) {
// TODO Auto-generated constructor stub
}
public double Length()
{
return Math.sqrt(Math.pow((end.x - start.x), 2) + Math.pow((end.y - start.y),2));
}
#Override
public String toString() {
return "start point "+ start + " "+ "end point "+ end + " " + "lenght "+Length() ;
}
}
class ColoredLine extends Line {
public Color color;
public ColoredLine(Point p1, Point p2,Color color ) {
super(p1, p2);
this.color=color;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
#Override
public String toString() {
return "start point "+ start + " "+ "end point "+ end + " " + "lenght "+Length() + " \n line color "+color ;
}
}
class PolyLine extends Line implements Picture{
int numSides =0;
Line sideLengths[];
public PolyLine(Line[] l1) {
super(l1);
sideLengths = l1;
numSides = l1.length;
// TODO Auto-generated constructor stub
}
#Override
public void Draw() {
System.out.println(" "+"number of sides "+ numSides + " "+ "coordinates of the beginning and end of the lines that make up the polygon\n"+ Arrays.toString(sideLengths) + " " ) ;
}
}
public class FourthLab {
public static void main(String[] args) {
ColoredPoint A = new ColoredPoint(3.5,4.0, Color.Blue);
System.out.println("A = " + A.toString());
ColoredPoint B = new ColoredPoint();
System.out.println("B = " + B.toString());
ColoredPoint C = new ColoredPoint(0.0,4.0, Color.Orange);
System.out.println("C = " + C.toString());
Line L1 = new Line (A,B);
Line L2 = new Line (B,C);
Line L3 = new Line (C,A);
System.out.println("L1 = \n" + L1.toString());
Line Colored_L1 = new ColoredLine (A,B,Color.getRandomColor());
System.out.println("L1_colored = \n" + Colored_L1.toString());
Line[] l1 = {L1,L2,L3};
PolyLine Triangle = new PolyLine (l1) ;
System.out.println("Triangle = \n" + Triangle.toString());
}
}
The output you are seeing fro the first version has nothing whatsoever to do with the Picture interface. You are seeing it because you are printing the instance to STDOUT, with something like:
System.out.println(myObj);
which in turn uses the toString() method, which you overrode.
Try:
Systenm.out.println(myObj.Draw());
An interface with a public String toString(); is useless/pointless, because since the Object class has that method, every object has that method.
I'm almost done with this java game project. I just have to add a defeated enemy's money to the main character's bag. I also have to add weapons and armor if they are better than the main character's weapons and armor. How do I add the enemy's money to the main character's money? In my mind, main_ch.getBag().getMoney() = main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney(); should work, but it doesn't.
Here is my main class:
import java.util.Scanner;
import Character.Character;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("> Welcome to The Game Project <");
System.out.println("\n >> Input Main Character Name: ");
String main_name = scanner.nextLine();
System.out.println(">> Input Main Character Power: ");
int main_power=scanner.nextInt();
System.out.println(">> Input Main Character Hp: ");
int main_hp=scanner.nextInt();
System.out.println("----------------------------------------------------");
Character main_ch=new Character (main_hp,main_power,main_name);
show_status(main_ch);
check_bag(main_ch);
Character enemies[]=new Character [10];
enemies[0]= new Character("Werewolf");
enemies[1]= new Character("Vampire");
enemies[2]= new Character("Alien");
enemies[3]= new Character("Witch");
enemies[4]= new Character("Ghost");
enemies[5]= new Character("Skeleton");
enemies[6]= new Character("Zombie");
enemies[7]= new Character("Demon");
enemies[8]= new Character("Mummy");
enemies[9]= new Character("Dragon");
boolean check = false;
int dead_count=0;
while(true) {
Random rnd=new Random();
int selected = rnd.nextInt(enemies.length); //random enemy selected
System.out.println();
System.out.println(">>>>> An enemy has appeared! <<<<<");
while(enemies[selected].getHp()>0) {
System.out.println();
System.out.println(">>>>> "+enemies[selected].getName()+" wants to fight!");
show_status(enemies[selected]);
check_bag(enemies[selected]);
System.out.println();
System.out.println(">> What do you want to do?");
System.out.println("\t1. Fight!");
System.out.println("\t2. Use skill.");
System.out.println("\t3. Check your stats.");
int input = scanner.nextInt();
if(input==1) {
int damageToEnemy = main_ch.hit_point();
int damageTaken = enemies[selected].hit_point();
enemies[selected].hp -= damageToEnemy;
main_ch.hp -= damageTaken;
if(enemies[selected].hp <= 0) {
enemies[selected].hp=0;
dead_count=dead_count+1;
main_ch.level=main_ch.level+1; //gain one level after enemy defeated
System.out.println(">> You defeated the enemy and gained a level!");
// The below code also doesn't work.
int pickUpMoney = main_ch.getBag().getMoney();
pickUpMoney=main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney();
System.out.println();
System.out.println("You found "+enemies[selected].getBag().getMoney()+" dollars. You now have "+main_ch.getBag().getMoney()+" dollars in your bag."); //take defeated enemy's money
for(int i = 0; i<4; i++) {
if(enemies[selected].getWeapon().getPower() > main_ch.getWeapon().getPower()) {
main_ch.getBag().getWeaponArray()[i]=enemies[selected].getBag().getWeaponArray()[i];
System.out.println("You found better weapons! They have been added to your bag.");
}
}
for(int i = 0; i<4; i++) {
if(enemies[selected].getArmor().getDefense()>main_ch.getArmor().getDefense()) {
main_ch.getBag().getArmorArray()[i]=enemies[selected].getBag().getArmorArray()[i];
System.out.println("You found better armor! They have been added to your bag.");
}
}
break;
}
System.out.println("\n>> You caused "+ damageToEnemy +" damage to the enemy! Their hp is now "+ enemies[selected].hp+".");
System.out.println(">> You received "+ damageTaken +" damage from the enemy! Your hp is now "+main_ch.hp+".");
if(main_ch.hp <=0) {
System.out.println();
System.out.println(">> Oh no! You died! Better luck next time. Thanks for playing!");
System.out.println();
break;
}
}
else if(input==2) {
if(main_ch.getSkill()>0 && main_ch.getMp()>0) {
main_ch.useSkill();
System.out.println("\t>> You used a skill. Your hit point increased to "+main_ch.hit_point()+". Your MP decreased to "+main_ch.getMp()+".");
}
else {
if(main_ch.getSkill()<=0) {
System.out.println("You have no skill points left.");
}
else{
System.out.println("\t>> Your MP is too low to use skill.");
}
}
}
else if(input==3) {
System.out.println();
show_status(main_ch);
check_bag(main_ch);
}
else {
System.out.println(">> You have entered an invalid key.");
}
}
if(dead_count==enemies.length) {
check=true;
}
if(check) {
System.out.println();
System.out.println(">>>>>>>>>> You won! Congratulations, you defeated all of your enemies! <<<<<<<<<");
break;
}
if(main_ch.hp <=0) {
System.out.println();
System.out.println(">> Oh no! You died! Better luck next time. Thanks for playing!");
System.out.println();
break;
}
}
}
public static void show_status(Character character) {
System.out.println("----------------- Character Status -----------------");
System.out.println("\tCharacter Name:\t\t"+character.getName());
System.out.println("\tCharacter HP:\t\t"+character.getHp());
System.out.println("\tCharacter Power:\t"+character.getPower());
System.out.println("\tCharacter Defense:\t"+character.getDefense());
System.out.println("\tCharacter MP:\t\t"+character.getMp());
System.out.println("\tCharacter Level:\t"+character.getLevel());
System.out.println("\tCharacter Hit Point:\t"+character.hit_point());
System.out.println("\tCharacter Skill:\t"+character.getSkill());
System.out.println("\tWeapon Name:\t\t"+character.getWeapon().getName());
System.out.println("\tWeapon Power:\t\t"+character.getWeapon().getPower());
System.out.println("\tArmor Name:\t\t"+character.getArmor().getName());
System.out.println("\tArmor Defense:\t\t"+character.getArmor().getDefense());
System.out.println("----------------------------------------------------");
}
public static void check_bag(Character character) {
System.out.println("-------------------- Bag Status --------------------");
System.out.println("\tMoney:\t\t\t$"+ character.getBag().getMoney());
for(int i = 0; i<4; i++) {
System.out.println("\tWeapon Name/Power:\t"+ character.getBag().getWeaponArray()[i].getName()+" // "+character.getBag().getWeaponArray()[i].getPower());
}
for(int i = 0; i<4; i++) {
System.out.println("\tArmor Name/Defense:\t"+ character.getBag().getArmorArray()[i].getName()+" // "+character.getBag().getArmorArray()[i].getDefense());
}
System.out.println("----------------------------------------------------");
}
}
Here is my Character class:
package Character;
import java.util.Random;
import Equipment.*;
public class Character {
private Armor armor = new Armor();
private Weapon weapon = new Weapon();
private Bag bag = new Bag();
public static String server_name = "CS172";
public int hp, power, defense, mp, level, skill;
private String name;
Random rnd=new Random();
public Character(String name) {
this.name=name;
Random rnd=new Random();
this.hp=rnd.nextInt(500)+1;
this.power=rnd.nextInt(100)+1;
this.defense=rnd.nextInt(100)+1;
this.mp=rnd.nextInt(50)+1;
this.level=1;
this.skill=5;
}
public Character(int hp, int power, String name) {
this.hp=hp;
this.power=power;
this.name=name;
this.defense=rnd.nextInt(100)+1;
this.mp=rnd.nextInt(50)+1;
this.level=1;
this.skill=5;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public int getMp() {
return mp;
}
public void setMp(int mp) {
this.mp = mp;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getName() {
return name;
}
public int damage(int enemy_power) {
int damage = enemy_power - this.defense;
if(damage<0){ //avoid healing by damage
damage=0;
}
this.hp=this.hp - damage;
if(this.hp<0) { //avoid negative hp
this.hp = 0;
}
return damage;
}
public Armor getArmor() {
return armor;
}
public void setArmor(Armor armor) {
this.armor = armor;
}
public Weapon getWeapon() {
return weapon;
}
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
public int hit_point() {
int total_power = this.power + this.weapon.getPower();
return total_power;
}
//------------------------------------------------------why isn't this increasing the hit point at all?
public int useSkill() {
this.mp=this.mp-1;
this.skill--;
return this.hit_point()+30;
}
public int getSkill() {
return skill;
}
public Bag getBag() {
return bag;
}
public void setBag(Bag bag) {
this.bag = bag;
}
public class Bag{
Weapon weaponArray[] = new Weapon[4];
Armor armorArray[] = new Armor[4];
int money = 150;
public Bag(){
for(int i=0; i<weaponArray.length; i++) {
weaponArray[i] = new Weapon();
armorArray[i] = new Armor();
}
}
public Weapon[] getWeaponArray() {
return weaponArray;
}
public void setWeaponArray(int yourWeaponIndex, Weapon enemyWeapon) {
this.weaponArray[yourWeaponIndex] = enemyWeapon;
}
public Armor[] getArmorArray() {
return armorArray;
}
public void setArmorArray(Armor[] armorArray) {
this.armorArray = armorArray;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
}
You are calling an accessor method like it will also set, which it doesn't. Try something like this:
main_ch.getBag().setMoney(main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney());
I have two classes called Pokemon.java and Move.java which contain methods for creating and modifying Pokemon and their moves. I've created all of the required methods, but I'm having trouble with the attack method, which is supposed to subtract an opponent's health when it's attacked.
Here is the code for the Pokemon.java class:
import java.util.ArrayList;
public class Pokemon
{
// Copy over your code for the Pokemon class here
// Private constants
private static final int MAX_HEALTH = 100;
private static final int MAX_MOVES = 4;
private String name;
private int health;
private int opponentHealth;
public static int numMovesForPokemon = Move.getNumOfMoves();
private Move move;
private static ArrayList<Move> moveListForPokemon = new ArrayList<Move>();
private String pokemonImage;
// Write your Pokemon class here
public Pokemon(String theName, int theHealth)
{
name = theName;
if(theHealth <= MAX_HEALTH)
{
health = theHealth;
}
}
public Pokemon(String name, String image)
{
this.name = name;
health = 100;
pokemonImage = image;
}
public Pokemon(String theName)
{
name = theName;
}
public void setImage(String image)
{
pokemonImage = image;
}
public String getImage()
{
return pokemonImage;
}
public String getName()
{
return name;
}
public int getHealth()
{
return health;
}
public boolean hasFainted()
{
if(health <= 0)
{
return true;
}
else
{
return false;
}
}
public boolean canLearnMoreMoves()
{
if(numMovesForPokemon < 4)
{
return true;
}
else
{
return false;
}
}
public boolean learnMove(Move other)
{
if(canLearnMoreMoves())
{
moveListForPokemon = Move.getList();
moveListForPokemon.add(other);
numMovesForPokemon++;
return true;
}
else
{
return false;
}
}
public void forgetMove(Move other)
{
moveListForPokemon.remove(other);
}
public static ArrayList<Move> displayList()
{
return moveListForPokemon;
}
public boolean knowsMove(Move move)
{
if(moveListForPokemon.contains(move))
{
return true;
}
else
{
return false;
}
}
public boolean knowsMove(String moveName)
{
if(moveListForPokemon.contains(move.getName()))
{
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, Move move)
{
if(knowsMove(move))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, String moveName)
{
if(knowsMove(moveName))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
return true;
}
else
{
return false;
}
}
public String toString()
{
return pokemonImage + "\n" + name + " (Health: " + health + " / " + MAX_HEALTH + ")";
}
// Add the methods specified in the exercise description
}
Here is the code for the Move.java class:
import java.util.ArrayList;
public class Move
{
// Copy over your code for the Move class here
private static final int MAX_DAMAGE = 25;
private String name;
private int damage;
public static int numMoves;
private static ArrayList<Move> moveList = new ArrayList<Move>();
public Move(String theName, int theDamage)
{
name = theName;
if(theDamage <= MAX_DAMAGE)
{
damage = theDamage;
}
}
public String getName()
{
return name;
}
public int getDamage()
{
return damage;
}
public static int getNumOfMoves()
{
return numMoves;
}
public static ArrayList<Move> getList()
{
return moveList;
}
public String toString()
{
return name + " (" + damage + " damage)";
}
// Add an equals method so we can compare Moves against each other
public boolean equals(Move other)
{
if(name.equals(other.getName()))
{
return true;
}
else
{
return false;
}
}
}
Finally, here is the code for PokemonTester.java where I test out the methods:
public class PokemonTester extends ConsoleProgram
{
private PokemonImages images = new PokemonImages();
public void run()
{
// Test out your Pokemon class here!
Pokemon p1 = new Pokemon("Charrizard", 100);
Pokemon p2 = new Pokemon("Pikachu", 100);
Move m1 = new Move("Flamethrower", 20);
Move m2 = new Move("Fire Breath", 15);
p1.learnMove(m1);
System.out.println(p1.knowsMove(m1));
System.out.println(p1.knowsMove("Flamethrower"));
System.out.println(p1.attack(p2, m1));
System.out.println(p2.getHealth());
}
}
I suppose your problem is this:
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
This code has several problems:
I'd suggest using a local variable for opponentHealth instead of a class level field
The opponent doesn't gets to know that it's health was subtracted. You have to share this knowledge with him, e.g. by introducing a setter for health and then calling opponent.setHealth(opponentHealth)
You are first assigning the value of Oponent.getHealth() to the int variable oponentHealth which you then modify, however this modification does not affect the health of Opponent but instead just the oponentHealth variable, you either have to directly access and modify the health field of Opponent or implement some kind of setHealth(int health) method in the class Pokemon
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting this error in my code. Can someone fix it and how is the code written? Can it be improved by maybe using setters and getters only?
Exception in thread "main" java.lang.NullPointerException
at Player.attack(Player.java:72)
at Main.main(Main.java:15)
My code:
Player.java
public class Player {
String name;
String race;
int hp;
int power;
int armour;
Weapon weapon;
public Player (String n, String r, int h, int p, int a) {
name = n;
race =r;
hp = h;
power = p;
armour = a;
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setRace (String r) {
race = r;
}
public String getRace() {
return race;
}
public void setHP (int h) {
hp = h;
}
public int getHP() {
return hp;
}
public void setPower (int p) {
power = p;
}
public int getPower() {
return power;
}
public void setArmour (int a) {
armour = a;
}
public int getArmour() {
return armour;
}
public boolean dead() {
return hp <= 0;
}
public boolean equip(Weapon weapon) {
this.weapon = weapon;
return true;
}
public boolean receiveDamage(int i) {
if ((hp - i) > 0) {
hp = hp - i;
return true;
}
hp = 0;
return false;
}
public boolean attack(Player player) {
return player.receiveDamage(weapon.useWeapon());
}
}
Main.java
public class Main {
public static void main(String args[]) {
Player Mensch = new Player("Mensch", "Mensch", 85, 12, 10);
Player Ork = new Player("Shrek", "Ork", 50, 14, 6);
Weapon MenschW = new Weapon("mächtiges Schwert", 15, 100);
Weapon OrkW = new Weapon("große Axt", 7, 100);
Mensch.equip(Mensch.weapon);
Ork.equip(Ork.weapon);
while (!Mensch.dead() && !Ork.dead() ) { //Alternativ: for (player hp >=0)
System.out.println("Mensch gegen Ork " + Mensch.attack(Ork));
if (Mensch.dead() || Ork.dead()) {
break;
}
System.out.println("Mensch gegen Ork " + Ork.attack(Mensch));
}
System.out.println("Ork ist tot: " + Ork.dead());
System.out.println("Mensch ist tot: " + Mensch.dead());
}
}
Weapon.java
import java.util.concurrent.ThreadLocalRandom;
public class Weapon {
String name;
int damage;
int hp;
public Weapon(String string, int d, int hp) {
// TODO Auto-generated constructor stub
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setDamage (int d) {
damage = d;
}
public int getDamage() {
return damage;
}
public void setWHP (int h) {
hp = h;
}
public int getWHP() {
return hp;
}
public int useWeapon() {
if
(broken())
return 0;
hp = hp - 5;
return (damage / 2) + random();
}
private int random() {
return ThreadLocalRandom.current().nextInt(1, damage + 1);
}
private boolean broken() {
return hp <= 0;
}
}
I know its a lot of code but I keep getting the same error, also I'm quite new to java so I would appreciate some tips or suggestions to make my code better or more failsave. The code doesn't do much yet but it will (hopefully) be a simple game soon in which two characters fight eachother with some calculations on damageoutput of each player. In this case a Human and Ork. Feel free to try it out
Change
Mensch.equip(Mensch.weapon); // Mensch.weapon is not initialized in constructor so it is null.
Ork.equip(Ork.weapon); // Ork.weapon is not initialized in constructor so it is null as well.
To
// Use your newly created weapons in the main instead.
Mensch.equip(MenschW );
Ork.equip(OrkW);
I'm working on an exercise which simulates an air traffic control tower with weather tracking features.
I have a coordinates class which has a private constructor. The constructor takes 3 arguments, longitude, latitude and height.
An aircraft class which takes with the arguments Coordinates coordinates and name. The aircraft class is inherited by 3 classes JetPlane, Helicopter and Baloon whose constructors take the same arguments as Aircraft.
As part of the exercise I have to use a factory class to create any of the 3 objects. My problem is that the factory method takes as arguments name, type, longitude, latitude and height but the objects which it returns ask for a Coordinates object.
How can I tell it that it should take the parameters from the factory class to make the Coordinates object? I have tried with a makeCoordinates method but if I set it to static that all coordinates will be 0. Is there any way to call it without it being static and without having to create a Coordinates object?
As part of the exercise I am not allowed to remove or add any parameters and access specifiers or change their type. So the Coordinates constructor will have to remain private.
(Flyable is an interface with a register and update method)
Here is the Coordinates class
public class Coordinates {
private int longitude;
private int latitude;
private int height;
public int getLongitude() {
return longitude;
}
public void setLongitude(int longitude) {
this.longitude = longitude;
}
public int getLatitude() {
return latitude;
}
public void setLatitude(int latitude) {
this.latitude = latitude;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
private Coordinates(int latitude, int longitude, int height){
}
public static Coordinates makeCoordinate(int longitude, int latitude, int height) {
return new Coordinates(longitude, latitude, height);
}
}
The factory class
public class ConcreteAircraftFactory extends AircraftFactory {
public Flyable newAircraft (String type, String name, int longitude, int latitude, int height){
Coordinates coord = Coordinates.makeCoordinate(longitude, latitude, height);
if (type.equals("Baloon") || type.equals("baloon")) {
return new Baloon(name, coord);
}
else if(type.equals("JetPlane") || type.equals("jetplane") || type.equals("Jetplane")) {
return new JetPlane(name, coord);
}
else if(type.equals("Helicopter") || type.equals("helicopter")) {
return new Helicopter(name, coord);
}
else
return null;
}
}
The Aircraft class
public class Aircraft {
protected long Id;
protected String name;
protected Coordinates coordinates;
private long idCounter;
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public long getIdCounter() {
return idCounter;
}
public void setIdCounter(long idCounter) {
this.idCounter = idCounter;
}
public Aircraft( String name, Coordinates coordinates) {
this.name = name;
this.coordinates = coordinates;
}
private long nextId() {
Id = getIdCounter() +1;
idCounter++;
return Id;
}
}
And one of the 3 classes which inherit Aircraft
public class Baloon extends Aircraft implements Flyable {
private WeatherTower weatherTower;
private String text;
public Baloon( String name, Coordinates coordinates) {
super( name, coordinates);
}
public void updateConditions() {
String newWeather = weatherTower.getWeather(coordinates);
switch(newWeather) {
case WeatherType.FOG:
coordinates.setHeight(coordinates.getHeight()-3);
text ="Baloon #" + this.getName() + "(" + this.getId() + "): get us lower, we are flying through pea soup";
try(PrintWriter out = new PrintWriter("Simulation.txt")){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
case WeatherType.RAIN:
coordinates.setHeight(coordinates.getHeight()-5);
text ="Baloon #" + this.getName() + "(" + this.getId() + "): descending will not make us any less wet";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
case WeatherType.SUN:
coordinates.setHeight(coordinates.getHeight()+4);
coordinates.setLongitude(coordinates.getLongitude()+2);
text ="Baloon #" + this.getName() + "(" + this.getId() + "): make twoards the rising sun";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
case WeatherType.SNOW:
coordinates.setHeight(coordinates.getHeight()-15);
text ="Baloon #" + this.getName() + "(" + this.getId() + "): this thing does not run a cold air";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
}
if(coordinates.getHeight()<0) {
coordinates.setHeight(0);
}
if(coordinates.getHeight()>100) {
coordinates.setHeight(100);
}
if (coordinates.getHeight()==0) {
weatherTower.unregister(this);
String text ="Tower Says: Baloon #" + this.getName() + "(" + this.getId() + "): has been unrergistered";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public void registerTower(WeatherTower weatherTower) {
weatherTower.register(this);
text ="Tower Says: Baloon #" + this.getName() + "(" + this.getId() + "): registered to weather tower";
try(PrintWriter out = new PrintWriter("Simulation.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Actually the factory method of Coordinates invokes the Coordinates private constructor but it has an empty body.
So it doesn't value any field of Coordinates :
private Coordinates(int latitude, int longitude, int height){
}
Just set the fields of the currently created object with the passed parameters :
private Coordinates(int latitude, int longitude, int height){
this.latitude = latitude;
this.longitude= longitude;
this.height= height;
}