I'm making a game right now and I'm trying to setup a CreatePlayer method.
In the main class, I take the Player class as an object to get its variables, methods ect.
package com.deud07.main;
import com.deud07.player.Player;
public class Main {
public static Player player = new Player("Bob", 86, null);
public static void main(String[] args) {
System.out.println(player.Position);
}
}
The 3rd parameter of Player is the Position, which is an array.
The problem I'm having is that I'm not sure how to set each element of the array without writing:
position[0] = 1f;
position[1] = -6f;
position[2] = 0f;
The code for Player:
package com.deud07.player;
public class Player {
public static String Name;
public static int ID;
public static float x;
public static float y;
public static float z;
public static float[] Position = {x, y, z};
public Player(String name, int id, float[] pos) {
Player.Name = name;
Player.ID = id;
Player.Position = pos;
}
public void createPlayer(String name, int id, float[] pos) {
Player player = new Player(name, id, pos);
player.Name = name;
player.ID = id;
player.Position = pos;
}
}
Any solutions? And while you're at it, anything I can do to fix up my code?
I believe you're asking for a shorthand method. You might also find them as "one liners". The way to initiate an array in one line without a variable is as follows:
Player player = new Player("Bob", 86, new float[]{1f, -6f, 0f});
As for "fixing your code", it goes outside of the actual question you've posted. Two things I can say are
Java conventions state that variables must be camel case. So your Player class' attributes should be name, id and position.
Your method createPlayer() does exactly the same the constructor does, thus it is not necessary. To create a new Player, just use... well, new Player().
Also, x, y and z are kind of useless. If you need x for example, just use position[0] instead.
Related
So I just started with java, so this is just a simple problem ig, but I have to make a small project for school. I made 2 classes, one called Pokémon and one called trainer. In the Pokémon class I made a constructor and a method to create objects, because I couldn't just create the object:
public class Pokemon {
public String name;
public String typ;
public int maxLp;
public int aktLp;
public int ap;
public Pokemon(String pname, String ptyp, int pmaxLp, int paktLp, int pap) {
name=pname;
typ=ptyp;
maxLp=pmaxLp;
aktLp=paktLp;
ap=pap;
}
public void CreatePokemon(String[] args) {
Pokemon Squirtle = new Pokemon("Squirtle", "Water", 20, 20, 5);
Pokemon Charmander = new Pokemon("Charmander", "Fire", 20, 20, 5);
}
}
In the other class, Trainer, I wanted to use these created objects (Pokemon Squirtle and Pokemon Charmander) to let them fight, the "fight" is basically just one pokemon, I wanted to use Squirtle in the function Squirtle attack, attacking Charmander dealing as much damage as declared in ap, changing the variable aktLp in the object Glumanda, which is the current hp of glumanda:
public class Trainer
{
public String name;
public String gender;
public int money;
public int amountPokemon;
public int amountFights;
public Trainer(String tname, String tgender, int tmoney, int tamountPokemon, int tamountFights) {
name=tname;
gender=tgender;
money=tmoney;
amountPokemon=tamountPokemon;
amountFights=tamountFights;
}
public void ChooseSquirtle() {
System.out.println("You choose Squirtle!");
}
public void ChooseCharmander() {
System.out.println("You choose Charmander!");
}
public void SquirtleAttack() {
System.out.println("Squirtle attacks Charmander!");
Charmander.aktLp = Charmander.aktLp - Squirtle.ap;
}
}
So for this project I have to use - even if I don't like it - BlueJ. BlueJ says: "cannot find symbol - variable Glumanda" - but why? Do I have to call the method CreatePokemon() ? Well I thought I had to and added CreatePokemon(); ,pressed compile and there was another error, but there is no explanation whatsoever. I can't find the problem even though it might be easy. As I said I pretty much just started with java so tips are appreciated - also, I tried my best translating the variables, sorry if you don't understand them and if they are inacurrate.
Your code is not very abstract and has a few flaws:
You're creating pokemon object inside the pokemon class definition. What you should do instead is create it in some higher level method, e.g.: main.
The trainer class uses two pokemons to attack each other. The problem is, the pokemon classes have not been instantiated in a scope that trainer can access. What you should do instead is either instantiate a new pokemon inside the trainer class, or pass pokemon objects as parameters to the generic attack function.
The trainer class could like this with instantiating new pokemon inside.
class Trainer {
public String name;
public String gender;
public int money;
public int amountPokemon;
public int amountFights;
private Pokemon squirtle;
private Pokemon charmander;
public Trainer(String tname, String tgender, int tmoney, int tamountPokemon, int tamountFights) {
name = tname;
gender = tgender;
money = tmoney;
amountPokemon = tamountPokemon;
amountFights = tamountFights;
squirtle = new Pokemon("Squirtle", "Water", 20, 20, 5);
charmander = new Pokemon("Charmander", "Fire", 20, 20, 5);
}
public void ChooseSquirtle() {
System.out.println("You choose Squirtle!");
}
public void ChooseCharmander() {
System.out.println("You choose Charmander!");
}
public void SquirtleAttack() {
System.out.println("Squirtle attacks Charmander!");
charmander.aktLp = charmander.aktLp - squirtle.ap;
}
}
Or like this with accepting pokemons as parameters:
class Trainer {
public String name;
public String gender;
public int money;
public int amountPokemon;
public int amountFights;
public Trainer(String tname, String tgender, int tmoney, int tamountPokemon, int tamountFights) {
name = tname;
gender = tgender;
money = tmoney;
amountPokemon = tamountPokemon;
amountFights = tamountFights;
}
public void SquirtleAttack(Pokemon attacker, Pokemon defender) {
System.out.println(attacker.name+" attacks "+defender.name+"!");
defender.aktLp = defender.aktLp - attacker.ap;
}
}
public class Main {
public void CreatePokemon(String[] args) {
Pokemon squirtle;
Pokemon charmander;
squirtle = new Pokemon("Squirtle", "Water", 20, 20, 5);
charmander = new Pokemon("Charmander", "Fire", 20, 20, 5);
}
}
Just a couple of hints:
Not sure what your project structure is, but you cannot have 2 public classes in a single file. Public class has to have the same name as filename. You can, however, have multiple non-public classes in a single file. But generally it is not recommended to define multiple classes in a single file anyways.
Per Java naming conventions, you should name variables or object instances beggining with lowercase letter. Read more: https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html
Try to use public class properties as least as possible and private as often as possible. To manipulate private properties values, use getters and setters. more info here: https://www.freecodecamp.org/news/java-getters-and-setters/
I want to code a little text adventure/dungeon crawler type of game. At the moment I have the classes Creature, Player, and Enemy. The classes Player and Enemy are subclasses of Creature.
I want to make the level of the enemy dependent on the level of the player. So for example, the enemy's level should always be 1 level above the player's level. So when the player is level 4 you should only be able to face enemies which are level 5.
My idea was to put something like this in the constructor of the Enemy class:
public Enemy(String name, int hp, int atk, int exp) {
super(name, Player.getLevel + 1, hp, atk);
this.exp = exp;
}
But that is clearly not allowed. Now I have no idea how to achieve this result. I lack some basic understanding of Java, but I'm willing to learn.
My code looks like this at the moment. I left the getters and setters out for better readability.
public class Creature {
private String name;
private int level;
private int hp;
private int atk;
public Creature (String name, int level, int hp, int atk){
this.name = name;
this.level = level;
this.hp = hp;
this.atk = atk;
}
}
public class Player extends Creature {
private int currentEXP;
private int expBar;
public Player(String name) {
super(name, 1, 100, 10);
this.currentEXP = 0;
this.expBar = 50;
}
}
public class Enemy extends Creature {
int exp;
public Enemy(String name, int level, int hp, int atk, int exp) {
super(name, level, hp, atk);
this.exp = exp;
}
}
First of all, the private modifier makes level unavailable in the subclasses. To solve that, you can either make change private to protected (or nothing / default), or you can provide an accessible getter method (int getLevel() { return level; }).
Your Enemy constructor takes a level argument, so to implement the player level + 1 feature, you can simply pass player.getLevel() + 1, alternatively pass player.getLevel() and let the constructor take care of adding 1.
The method using these classes (assuming main for now) would look something like this:
public static void main(String[] args) {
Player p = new Player("Player1");
Enemy e = new Enemy("Enemy1", p.getLevel() + 1, 100, 10, 40);
}
To clarify, the reason why Player.getLevel + 1 doesn't work is because Player is a class, but you need a Player object (i.e. the result of calling new Player(...)) to refer to instance fields or methods, such as getLevel.
How do I refer to a certain parameter of my Object that is queued up in my list?
We're currently working with lists and Im trying to compare a parameter with a specific parameter of an Object that is in my list. The class list only offers getContent(), but I don't need the object I need the parameter inside the object.
if (answer.equals(a)) {
vocList.getContent(Vocabulary.getGerman());
}
I've got a getter in the class Vocabulary. Vocabulary is queued in my List
Vocabulary class:
public class Vocabulary {
private String deutsch;
private String englisch;
public Vocabulary(String pGerman, String pEnglish)
{
english = pEnglish;
german = pGerman;
}
public String getGerman()
{
return german;
}
public String getEnglish()
{
return english;
}
}
To get the value of an object you need the getter you created in the Vocable class:
vocList.get(i).getGerman(); //i is the index of the object in your list.
So your Vocable class should look like this to actually store the values you create the objects with:
public class Vocable{
private String german;
private String english;
public Vocable(String pGerman, String pEnglish){
english = pEnglish;
german = pGerman;
}
public String getGerman(){
return german;
}
public String getEnglish(){
return english;
}
}
This appears to be a homework question since you say, "We are currently working with lists." So, I'll try to steer you in the right direction without giving the answers away. I also recommend you read the Oracle Java Tutorial on Objects.
Now, to your question: You want to get a handle to the specific Object---once you have a handle for the Object, you can call its instance methods or access its fields' values. For example, suppose I have a Rectangle object:
public class Rectangle {
public int x;
public int y;
public int width;
public int height;
public Rectangle(int x, int y, int width, int height) {
this.X = x;
this.Y = y;
this.width = width;
this.height = height;
}
}
You can use the following code to print create a new Rectangle and then print its fields' values. Notice you have to get the element from the list (using get(0)) before I could access the Rectangle's variables. You have to do the same thing in your code, but it looks like you're using a custom List implementation; So, you'll have to use the getContent method to get a reference to the object.
public class CreateObjectDemo {
public static void main(String[] args) {
//create an ArrayList
static List<Rectangle> rectangleList = new ArrayList<Rectangle>();
//create a rectangle and add it to the array list
Rectangle rect = new Rectangle(50,50,100,75);
rectangleList.add(rect);
printFirstRectangle(rectangleList);
}
/** Prints the first rectangle in the list */
private static void printFirstRectangle(List<Rectangle> rectangles){
if (rectangles.size() > 0){ //if the list has at least one element
//get the handle for the first element---the one at the 0th index
Rectangle firstRect = rectangle.get(0);
//print the result
System.out.printf("First Rectangle, x=%d, y=%d, width=%d, height=%d\n",
firstRect.x,
firstRect.y,
firstRect.width,
firstRect.height);
} else { //if the list is empty
System.out.println("The list is empty.");
}
}
}
I need a bit of help here. so i have this. I was basically wondering when you create an array of object of a parent class, then change that object to a child class, can I access the methods of that child class and if not why. thanks for any help.
public class Racer {
private String name;
private int position;
// Constructor
public Racer()
{}
public Racer(String name)
{
this.name = name;
position = 0;
}
public String getName()
{
return name;
}
public int getPosition()
{
return position;
}
public void setPosition(int n)
{
position = n;
}
public void setName(String n){
this.name=n;
}
}
the child class
public class Spartiates extends Racer{
private int energy;
public Spartiates(){
super();
}
public Spartiates(String name){
setName(name);
setPosition(20);
energy=100;
}
public void setEnergy(int energy){
this.energy=energy;
}
public int getEnergy(){
return energy;
}
}
main class
public class demo{
public static void main(String[] args){
Racer [] player = new player[3];
for(int i=0; i<player.length; i++){
player[i] = new Spartiates();
}
System.out.println(player[1].getEnergy());
}
so here the problem the getEnergy method doesn't work so I was wondering why. If anybody can help it would be very much appreciated. thanks
This is discussed here:
Is it possible to call subclasses' methods on a superclass object?
Along with all the reasons why doing something like this is probably never a good idea :).
You'll have to cast it to an instance of the subclass. If you plan on having a mixed array of object instances you'd need to first check the type:
System.out.println(((Racer)player[1]).getEnergy());
You need either define the function in the superclass or cast the object to the subclass.
If you intend the array to hold ONLY elements of the subclass Spartiates, then declare it as such.
Otherwise, if it needs to hold objects of both type, there only way to do this is to check with instanceof.
if (player[1] instanceof Spartiates)
System.out.println(((Spartiates)player[1]).getEnergy());
else
// handle other types
The reason energy is 0 is because you are calling your empty (no arg) constructor:
player[i] = new Spartiates();
which does not initialize the energy variable (so it will be 0 by default). You only set the variable to 100 in the constructor which takes in a String, namely here:
public Spartiates(String name){
setName(name);
setPosition(20);
energy=100;
}
So either call that constructor in the for loop with some string as an argument, or call your setEnergy() setter with some value after creating the object with the empty constructor.
Also, this is wrong:
Racer [] player = new player[3];
It should read:
Racer [] player = new Racer[3];
or:
Racer [] player = new Spartiates[3];
I have a class file name serializedObject, I will like to call this class file in another class file and use it's method.
I want to declare the class file became and array to being use in another class file.
Then I declare something like below:
serializedObject[] setData = new serializedObject[10];
and use it into a for loop
for(int i=0; i<clientInfo.length; i++)
{
double locationX = clientInfo[i].getLocation().getX();
double locationY = clientInfo[i].getLocation().getY();
String name = clientInfo[i].getName();
double mood = clientInfo[i].getMood();
double hunger = clientInfo[i].getHunger();
double chargestate = clientInfo[i].getChargestate();
setData[i].setAll(locationX, locationY, name, mood, hunger, chargestate);
System.out.println(setData[i].getName());
}
In the serializedObject class I have the set method and also get method,
but seems like not work for this. What can i do instead of this way to get an array method?
Thanks for any comment and help.
The system seems like cant really set my value into the method,
i cant get the any value from the
System.out.println(setData[i].getName());
but the system doesn't have any compile error.
Here will be my serializedObject class file
public class serializedObject
{
public static double locationX;
public static double locationY;
public static String name;
public static double mood;
public static double hunger;
public static double chargestate;
public serializedObject()
{
}
public void setAll(double locationX,double locationY, String name,double mood,double hunger, double chargestate)
{
this.locationX = locationX;
this.locationY = locationY;
this.name = name;
this.mood = mood;
this.hunger = hunger;
this.chargestate = chargestate;
}
public String getName()
{
return this.name;
}
public double getLocationX()
{
return this.locationX;
}
public double getLocationY()
{
return this.locationY;
}
public double getMood()
{
return this.mood;
}
public double getHunger()
{
return this.hunger;
}
public double getChargestate()
{
return this.chargestate;
}
}
Note that this serializedObject[] setData = new serializedObject[10]; will just create the array. All elements are still null thus calling methods on those elements (like getName()) will result in a NullPointerException. You'd have to initialize the elements first: setData [0] = new serializedObject(); then you call call methods on the element.
First of all, by convention, the initial letter of a class name should be capitalized as such, SerializedObject. In your for-loop, you'll need to do the following:
for(int i = 0; i < clientInfo.length; i++)
{
// Construct new serialized object
setData[i] = new SerializedObject();
// Extract client information
double locationX = clientInfo[i].getLocation().getX();
double locationY = clientInfo[i].getLocation().getY();
String name = clientInfo[i].getName();
double mood = clientInfo[i].getMood();
double hunger = clientInfo[i].getHunger();
double chargestate = clientInfo[i].getChargestate();
// Store information in serialized object
setData[i].setAll(locationX, locationY, name, mood, hunger, chargestate);
// Add serialized object to array
System.out.println(setData[i].getName());
}
Note: At the moment, your program should be throwing a NullPointerException, which should have let you know that the elements within setData are null.
public static double locationX;
public static double locationY;
public static String name;
public static double mood;
public static double hunger;
public static double chargestate;
These properties are all static. That means they will be shared between all instances of serializedObject. Therefore, if you do setAll on one instance, it will seem to change every other instance.
You should make these instance members:
public double locationX;
public double locationY;
public String name;
public double mood;
public double hunger;
public double chargestate;
Fields should usually not be public, but that's a separate discussion.