I'm trying to build some Dota2-like classes, with simple details. I got stuck at one point where I need my hero's attribute in Main, but the constructor for it doesn't work. Here is the code for Hero class:
enum attribute {
Strength, Intelligence, Agility
};
public class Hero extends Unit {
private int level;
private static int str;
private static int intl;
private static int agi;
private static attribute heroAttribute;
public attribute getAttribute() {
return heroAttribute;
}
private static int attributeDamage() {
if (heroAttribute == attribute.Strength)
return str;
else if (heroAttribute == attribute.Intelligence)
return intl;
else
return agi;
}
public Hero(int level, int str, int intl, int agi, attribute heroAttribute) {
super(200 + 20 * str, attributeDamage());
System.out.println("A hero has been spawned.");
}
}
and the Main:
public class Main {
public static void main(String[] args) {
Hero h1= new Hero(25,400,30,30,attribute.Agility);
System.out.println(h1.getAttribute());
}
}
What I get is that I have null "attribute" value.
Try put this attributes without the static, and initiate these attributes...
private int str;
private int intl;
private int agi;
private attribute heroAttribute;
public Hero(int level, int str, int intl, int agi, attribute heroAttribute) {
this.str = str;
this.intl = intl;
this.ai = agi;
this.heroAttribute = heroAttribute;
super(200 + 20 * str, attributeDamage());
System.out.println("A hero has been spawned.");
}
i suggest you to create new enum class that containt those 3 attribute and then, implement them.
by the way, all enum entities should be upper case like: STRENGTH, AGILITY, INTELLIGENT
public enum HeroAttribute {
STRENGTH("str"),
AGILITY("agi"),
INTELLIGENT("intl");
private String literal;
HeroAttribute(String literal) {
this.literal = literal;
}
public String getLiteral() {
return literal;
}
}
Related
I need to write up a static method that takes an array of Vehicles and print each registration number in the array. The object in the array is either a Vehicle, a Car, or a Truck object reference. Finally, I need to print the registration number of the object on a single line on its own.
So the code is:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
public class Car extends Vehicle {
int passengers;
public Car(String rego, int pass) {
super(rego);
passengers = pass;
}
public int getPassengers() {
return passengers;
}
}
public class Truck extends Vehicle {
int tons;
public Truck(String rego, int tons) {
super(rego);
this.tons = tons;
}
public int getTons() {
return tons;
}
}
I have to write up a static method for the following test and get the following, but I am having some trouble.
Test and expected Result
This is what I have done so far:
public static void printRegNum(Vehicle[] list){
for (int i = 0; i < list.length; i++){
System.out.println(list[i]);
}
}
The 1st way to play with your System.out.println(list[i]); is to override the toString() method in class Vehicle:
public class Vehicle {
private String registrationNumber;
public Vehicle(String rego) {
registrationNumber = rego;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public String toString() {
return registrationNumber;
}
}
The 2nd way is change:
from:
System.out.println(list[i]);
to:
System.out.println(list[i].getRegistrationNumber());
Hope those can help.
Not getting where's the problem
i.e.
public static void main(String[] args){
Car car = new Car("MYCAR",4);
Truck t = new Truck("MYTRUCK", 16);
Vehicle[] myList = new Vehicle[] {car, t};
printRegNum(myList);
}
Also seems that you only need to print the "rego".
System.out.println(list[i].getRegistrationNumber());
These are two classes of code that I wrote.. the problem here is I am not sure how to define class fields to represent Grass, fire and water as a Type using static..
Also I am not sure if I had used the super function the right way.. How do I properly call the parent's constructor so that I dont have to re define "knockedOut boolean" and be able to use Fire as the type?
Question could be confusing but I am not sure how to explain it better :( sorry
public abstract class Pokemon {
private String name;
private String type;
private int attack;
private int health;
private boolean knockedOut;
static private String Grass;
static private String Water;
static private String Fire;
public Pokemon (String n, String t, int a, int h) {
name = n;//state
type = t;//state
attack = a;//state
health = h;//state
knockedOut = false;
}
public abstract int takeDamage(Pokemon enemy);
public String toString() {
return "}";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public boolean isKnockedOut() {
return knockedOut;
}
public void setKnockedOut(boolean knockedOut) {
this.knockedOut = knockedOut;
}
}
public abstract class Charizard extends Pokemon {
private static String Fire;
private int attackFire;
private int healthFire;
private static String Water;
private static String Grass;
public Charizard(int a, int h) {
super("Charizard", Fire, a, h);
attackFire = a;
healthFire = h;
}
public int takeDamage(Pokemon enemy){
int enemyAttack = enemy.getAttack();
if(enemy.getType().equals(Water)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Fire)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Grass)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()/2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
if(healthFire <=0){
Charizard.set = true;
}
}
return enemyAttack;
}
}
You want to declare your different types like this:
static public final String GRASS= "Grass";
static public final String WATER = "Water";
static public final String FIRE = "Fire";
(I'm following the established convention here that fields declared static, public, and final should have names in all uppercase letters.)
By declaring these fields public, any other classes (including those that extend Pokemon, such as Charizard) that might need to test the type of a Pokemon can use them. By declaring them final, nobody can change them even though they are public. By giving them initial values, you make them actually useful for distinguishing different types of Pokemon, as well as avoid the inevitable NullPointerException that would happen the first time you executed something like p.getType().equals(Pokemon.FIRE)
As for knockedOut, it looks like you're handling it the right way. The field knockedOut is private in Pokemon but you've provided public getter and setter methods that other classes can (and do) use to access it.
i'm a novice in java and i don't know how to call a variable from a private class to another.
Currently i'm using NetBeans 8.1 and here's the class from which i wanna take the values
public class Mars {
public static String name;
private static int fuel;
private static int AI;
private static int tecnology;
public void setName(String nm)
{
name = nm;
}
public void setFuel(int fl)
{
fuel = fl;
}
public void setAI(int ai)
{
AI = ai;
}
public void setTecnology(int tc)
{
tecnology = tc;
}
public String getName()
{
return name;
}
public int getFuel()
{
return fuel;
}
public int getAI()
{
return AI;
}
public int getTecnology()
{
return tecnology;
}
private static class name {
public name(){
name = "unknown";
}
}
private static class fuel{
public fuel() {
fuel = 50;
if ((fuel >100) || (fuel <0))
{System.out.println("\nError!");
System.exit(0);}}}
private static class AI {
public AI() {
AI = 5;
if ((AI >10) || (AI <1))
{System.out.println("\nError!");
System.exit(0);}}}
private static class tecnologiy {
public tecnologiy() {
tecnology = 5;
if ((tecnology >10) || (tecnology <1))
{System.out.println("\nError");
System.exit(0);}}}
}
And here is the class where i want to put the values:
public class Space_Battle {
public static void main(String[] args) {
Mars Call1 = new Mars();
System.out.println("\nThe alien named " + Mars.name + " joined the battle" );
}
}
Naturally every correction will be very appreciate! :-D
P.S. I'm sorry if this question is ridicoulos.
Change your code to this...
public class Space_Battle {
public static void main(String[] args) {
Mars mars = new Mars();
System.out.println("\nThe alien named " + mars.getName() + " joined the battle");
}
When you create an instance of an object, you should access it via secure accessors i.e. getter methods, getName(), etc.
And remove the static declaration from your private variables.
You cant directly set values to private variables from another class, thats why they are private.
You HAVE to instantiate an object of the said class.
Example:
Mars call1= new Mars();
then you can set values to that object.
call1.setName("whatever");
then to get the value of the object just use the getter.
call1.getName();
then to print it:
System.out.println("\nThe alien named " + call1.getName() + " joined the battle" );
Also, remove the static from your variables.
I would also encourage you to read about the "this" keyword.
I recommend you to read this documentation:
https://docs.oracle.com/javase/tutorial/java/concepts/object.html
I have a class Zeitpunkt which implements a date with time and in addition a class Suchbaum which represents a binary search tree.
I want to use a Comparator-Object in Suchbaum to sort a tree by the day of Zeitpunkt, but when I want to create a Suchbaum object, it prints the named error.
Zeipunkt
public class Zeitpunkt<T> implements Comparable<T>
{
private int jahr;
private int monat;
private int tag;
private int stunden;
private int minuten;
private double sekunden;
public int vergleich(Zeitpunkt a) { ... }
#Override
public int compareTo(T o) {
if(o instanceof Zeitpunkt)
return vergleich((Zeitpunkt)o);
return 0;
}
...
}
Suchbaum
public class Suchbaum<T extends Comparable<T>> {
private class Element {
private T daten;
private Element links;
private Element rechts;
public Element(T t) {
daten = t;
links = null;
rechts = null;
}
}
private Element wurzel;
private Comparator<T> comp;
...
}
Testclass
public class BaumTest {
public static void main(String[] args) {
// error in the following line (IntelliJ underlines the first
// "Zeitpunkt"). Suchbaum<Zeitpunkt<?>> = ... doesn't work either..
// *Completely confused*
Suchbaum<Zeitpunkt> sb = new Suchbaum<>((Zeitpunkt z1, Zeitpunkt z2) -> {
if(z1.getTag() > z2.getTag())
return 1;
else if(z1.getTag() == z2.getTag())
return 0;
else
return -1;
});
}
}
Any ideas? (the other threads with this topic didn't help me out)
Seems that you don't want to make your Zeitpunkt class parametrized, you just want it to implement Comparable interface. So change it like this:
public class Zeitpunkt implements Comparable<Zeitpunkt> {
private int jahr;
private int monat;
private int tag;
private int stunden;
private int minuten;
private double sekunden;
public int vergleich(Zeitpunkt a) {
return 0;
}
#Override
public int compareTo(Zeitpunkt o) {
return vergleich(o);
}
}
Also you need to define a constructor in your Suchbaum class:
public Suchbaum(Comparator<T> comp) {
this.comp = comp;
}
I have made a class called Fish:
public class Fish {
private String species;
private int size;
//Constructor
public Fish(int x, String s) {
size = x;
species = s;
}
public String getSpecies() { return species; }
public int getSize() { return size; }
public String toString() {
return String.format("A %dcm %s", size, species);
}
}
And I have also started to make a class called pond that is meant to have an attribute called 'fish' that holds an array of Fish objects. I am unsure of how to do this. Here is my attempt so far. I am
public class Pond {
private int capacity;
private Object[] fish; //This is what I am trying to initialize. list of Fish.
private int numFish;
//Capacity Constructor
public Pond(int n, int c) {
n = numFish;
c = capacity;
}
public int getNumFish() { return numFish; }
public boolean isFull() {
boolean isFull = false;
if (numFish >= capacity) {
isFull = true;
}
else {
isFull = false;
}
return isFull;
}
public String toString() {
return String.format("Pond with %d fish", numFish);
}
public void add(Fish aFish) {
if (numFish <= capacity) {
numFish += 1;
fish.add Fish;
}
else {
numFish += 0;
}
}
}
Change this:
private Object[] fish;
as follows:
private Fish[] fish;
i.e. these are fishes and not just any
kinds of objects (they not mammals e.g.).
Following is invalid -
fish.add aFish;
with arrays you do
fish[numFish] = aFish; //increment numFish after this
You also need to initialize your array
fish = new Fish[capacity];
in your constructor.
In the Pond constructor you're assigning private fields to constructor arguments. I think it should be the other way around:
public Pond(final int n, final int c) {
numFish = n;
capacity = c;
}
A side note: declaring Pond constructor arguments final would prevent these kind of error at compile time.
Also, if you want to expand fish array at runtime then array is not the best choice of the container type. ArrayList<Fish> is a better choice as it can expand at runtime.
You need to use ArrayList instead of Array since an ArrayList can grow according to requirements.
Take a look at this code.Should help you:
public class Fish {
String name;
public Fish(String name) {
this.name=name;
}
public String toString() {
return name;
}
}
And then:
import java.util.*;
public class Pond {
ArrayList<Fish> fishInPond = new ArrayList<>();
public void addFish(Fish e) {
fishInPond.add(e);
}
public void showFishes() {
for (int i= 0; i<fishInPond.size();i++) {
fishInPond.get(i);
}
System.out.println("Fishes in my pond: " + fishInPond);
}
public static void main(String[]args) {
Pond myPond = new Pond();
myPond.addFish(new Fish("Tilapia"));
myPond.addFish(new Fish("cat fish"));
myPond.showFishes();
}
}