I'm very new to coding and have a strict deadline for this assignment so I couldn't find an explanation I understood very well so I am asking here.
I am makign an instance of my Pokemon class in a another class for my main game. I however need info on how many times a pokemon was defeated in my catch pokemon class as I want a user to only be able to catch a pokemon if they've beat it a certain amount of times. I have no clue how to do this however.
This is how the class is used if it is of any help:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Battle extends JFrame{
public Pokemon fire = new Pokemon("Charmander", "Fire");
public Pokemon water = new Pokemon("Squirtle", "Water");
public Pokemon plant = new Pokemon("Bulbasaur", "Grass");
public Pokemon ground = new Pokemon("X", "Ground");
I have tried something like Battle.pikachu.toString() in the main class to just test how to access it because that is what someone else told me but the battle part confuses me as I don't think it is actually referrign to anything when in my main class.
You should not define your Pokemon inside a Battle. You should instead pass your Pokemon into this Battle class.
So you should instead define your Pokemon in your Main class:
public class Main {
// Your functions...
private ArrayList<Pokemon> getMyPokemons() {
ArrayList<Pokemon> myPokemonList = new ArrayList<>();
Pokemon fire = new Pokemon("Charmander", "Fire");
Pokemon water = new Pokemon("Squirtle", "Water");
Pokemon plant = new Pokemon("Bulbasaur", "Grass");
Pokemon ground = new Pokemon("X", "Ground");
myPokemonList.add(fire);
myPokemonList.add(water);
myPokemonList.add(plant);
myPokemonList.add(ground);
return myPokemonList;
}
private void triggerBattle() {
ArrayList<Pokemon> myPokemonList = getMyPokemons();
Battle battle = new Battle(myPokemonList);
}
}
And in your Battle class,
public class Battle extends JFrame {
private ArrayList<Pokemon> myPokemons;
// Create constructor to receive your Pokemon
public Battle(ArrayList<Pokemon> myPokemons) {
this.myPokemons = myPokemons;
}
// And in other functions within this class, you can access
// myPokemons list
}
And of course if you need more information related to the Pokemon, you need to refer to #Boycpu suggestion and add more attributes to your Pokemon class.
Do you mean?
public class Pokemon {
private String name;
private String group;
private int defeatedTimes;
public Pokemon(String name, String group, int defeatedTimes) {
this.name = name;
this.pass = group;
this.defeatedTimes = defeatedTimes;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getDefeatedTimes() {
return defeatedTimes;
}
public void setDefeatedTimes(int defeatedTimes) {
this.defeatedTimes = defeatedTimes;
}
}
Related
ItemStack is not serializable and I'm trying to save an object called Objective with an ItemStack field to a file but since ItemStack is not serializable this does not work. I tried extending ItemStack and implementing Serializable and changing the field to my new serializable sub class but this also did not work. Here are the relevant parts of my original code:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import org.bukkit.inventory.ItemStack;
public class Objective implements Serializable {
private static final long serialVersionUID = -2018456670240873538L;
private static ArrayList<Requirement> requirements = new ArrayList<>();
private String name;
private Requirement requirement;
private ItemStack reward;
private int tillComplete;
private boolean complete;
public Objective(String name, int requirementIndex, int tillComplete, ItemStack reward) {
if(requirements.isEmpty()) {
requirements.add(Requirement.kill_Skeletons);
requirements.add(Requirement.kill_Spiders);
requirements.add(Requirement.kill_Zombies);
}
this.name = name;
this.requirement = requirements.get(requirementIndex);
this.tillComplete = tillComplete;
this.reward = reward;
complete = false;
}
public String getName() {
return name;
}
public Object getRequirement() {
return requirement;
}
public static ArrayList<Requirement> getRequirements() {
return requirements;
}
public static void setRequirements(ArrayList<Requirement> requirements) {
Objective.requirements = requirements;
}
public int getTillComplete() {
return tillComplete;
}
public void setTillComplete(int tillComplete) {
this.tillComplete = tillComplete;
}
public void setName(String name) {
this.name = name;
}
public void setRequirement(Requirement requirement) {
this.requirement = requirement;
}
public void setReward(ItemStackSerializable reward) {
this.reward = reward;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
public ItemStack getReward() {
return reward;
}
public boolean isComplete() {
return complete;
}
}
Elsewhere in my code this line of code:
ItemStack reward = new ItemStack(Material.DIAMOND_SWORD);
Objective objective = new Objective(args[1] ,Integer.parseInt(args[2]), Integer.parseInt(args[3]), reward);
is giving me this error:
java.io.NotSerializableException: org.bukkit.inventory.ItemStack
How can I serialize this object? I need to store it but Java wont let me. Thanks for your help. If you need anymore code snippets or other information please let me know.
This is most likely an XY problem. ItemStack is not serializable, as it represents an actual stack of items at runtime. This would not make sense to store in a file. It might be worth looking at the ConfigurationSerializable interface, which is implemented by ItemStack, but I don't think you need that here.
In your example, the ItemStack that you are trying to serialize doesn't have any metadata. It is a single diamond sword. If all your rewards are just a single item, all you need to save is the Material and you can create a new ItemStack from that Material every time you want to give a player a reward. Since Material is an enum, it is serializable by default.
You could also serialize an int for stack size if some of your rewards require a stack of multiple items. If you need any metadata, serialize the data needed to construct that at runtime. For example, to give an item lore, you would store a List<String> (with a serializable implementation of List).
I'm a beginner Java programmer and I'm trying to check whether I've successfully copied an instance of Person in a linked list stored in class Clients to the linked list called passengers inside an instance of class Boat by having Boat print out the contents of it's linked list.
I am using the method givePassengers() from class Boat to have the Boat class printout it's passengers linked list contents.
However when I attempt to do so I am encountering the error 'non-static method givePassengers() cannot be referenced from a static context' and I'm not sure what to write to solve that problem. I've listed what I believe to be the problem code below. Any assistance is greatly appreciated.
I have marked important code with '// !!'
This is the class that contains the linked list of boats
import java.io.*;
import java.util.*;
public class Base implements Serializable
{ private LinkedList<Boat> boats = new LinkedList<Boat>();
private Clients clients = new Clients();
public void setup() // !! Here are the instances of the boat class
{ boats.add(new Boat(1, "Ed", 2));
boats.add(new Boat(2, "Fred", 7));
boats.add(new Boat(3, "Freda", 5)); }
public void showpassengers() {
for (Boat i: boats) `// !! The for each loop cycles through each boat to check for passengers`
Boat.givePassengers(); // !! This line produces the error
}
Here is the boat class
import java.io.*;
import java.util.*;
public class Boat implements Serializable
{ private int id;
private String pilot;
private int stops;
private LinkedList<Person> passengers = new LinkedList<Person>();
private double rate = 10.00;
public int scannableId = this.id;
public Boat(int id, String pilot, int stops)
{ this.id = id;
this.pilot = pilot;
this.stops = stops; }
public void givePassengers () {
System.out.println(passengers); // !! this line is supposed to print out the contents of the boat classes' linked list so I can check that it worked.
}
Here is the Person class
import java.io.*;
import java.text.*;
public class Person implements Serializable
{ private String name;
private int id;
private double cash = 100.00;
private int start = 0;
private int end = 0;
private double charge = 0;
public Person(String name, int id)
{ this.name = name;
this.id = id + 100; }
}
Here is the class that contains the linked list of Person
import java.io.*;
import java.util.*;
public class Clients implements Serializable
{ private LinkedList<Person> clients = new LinkedList<Person>();
private int id = 1;
public Clients() `// !! Here are the instances of Person in the class clients`
{ clients.add(new Person("Homer", id++));
clients.add(new Person("Marge", id++));
}
)
And here is the root class if that helps
import java.io.*;
public class Root
{ public Root() {
new Base();
}
public static void main(String[] args)
{ new Root(); }
private Base base;
}
Your problem is here:
for (Boat i: boats)
Boat.givePassengers(); // !! This line produces the error
You need to say i.givePassengers() to reference the specific instance of the class Boat. There's a good primer on the difference between classes and objects here.
You can't call givePassengers() statically from Boat, it's not a static method. You need to call it from an instance of Boat. Replace Boat.givePassengers(); with i.givePassengers(); within your foreach loop. This will cause the currently selected Boat instance to run givePassengers().
I created 2 instances of my class player, but it seems as though the last instance created always takes over (overlaps?) All of the other objects, what is the issue here?
Here is the program:
public class Test
{
public static void main (String[] args)
{
Player player1 = new Player("Player 1");
Player player2 = new Player("Player 2");
Player player3 = new Player("Player 3");
System.out.println(player1.getName());
}
}
This is the output
Player 3
And this is the class
import java.util.Scanner;
import java.util.Random;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Player
{
public static String name;
public static int score;
public static Die[] dice = new Die[5];
public static JRadioButton[] rerollButton = new JRadioButton[5];
//----------------------------------------------------------------
// Constructor - initialize values
//----------------------------------------------------------------
public Player(String n)
{
name = n;
score = 0;
// initialize all dice and rerollButtons in their respective arrays
for (int i = 0; i < 5; i++) {
dice[i] = new Die();
rerollButton[i] = new JRadioButton();
}
}
public String getName()
{
return name;
}
}
I have tried to look for other similar questions but every one I found was far to complex for me to really understand.
The attributes in your Player class such as name,score, dice etc are defined as class variables(static) instead of instances variables(non-static). Class/static variables are shared by all the objects and hence you see that behavior. Try changing this:
public static String name;
to
public String name;
Make a wise decision what you need to declare as class variable and what as member variable. Learn more about instance and class members here:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
That's because name is a static field in your Player class. And the static fields are shared by all the instances of a class. Therefore, you need to make the name as an instance variable, so that each instance will have their own copy of the it.
public String name; // Now each instance will have its own copy of name
and I'm guessing that the same needs to be done for score as well.
public int score;
public static String name;
should be
public String name;
or even better
private String name;
Because, your field is static,
public static String name;
To change the name with object make it as instance(non-static)
public String name;
I need to create my own registry for a school project.
I would like to have
1
room, room
2
room, room
hall, hall
3
room, room
hall, hall
dorm, dorm
But all I am getting is
1
room,room
2
room,hall
hall,hall
3
room,dorm
hall,dorm
dorm,dorm
So somehow the the facility reference got changed somewhere but i have no idea how to fix this. Can anyone help?
These are my codes.
public class registry {
static List<registryRecord> register = new ArrayList<registryRecord>();
public static boolean bind(String name, facility ref){
for(registryRecord r:register){
if(r.name.equals(name)) //check if the name is already binded
return false;
}
registryRecord newRecord = new registryRecord(name, ref);
register.add(newRecord);
for (registryRecord r:register){
System.out.println(r.name +","+ r.ref.name);
}
return true;
}
public class registryRecord {
String name;
facility ref;
public registryRecord(String name, facility ref){
this.name = name;
this.ref = ref;
}
public class server {
public static void main(String args[]) throws Exception{
facility room = new facility("room");
System.out.println(1);
boolean test = registry.bind("room", room);
facility hall = new facility("hall");
System.out.println(2);
boolean test2 = registry.bind("hall", hall);
facility dorm = new facility("dorm");
System.out.println(3);
registry.bind("dorm", dorm);
}
public class facility {
public static String name;
static List<booking> bookings;
public facility(String name){
this.name=name;
this.bookings = new ArrayList<booking>();
}
}
As I suspected, since name is static in facility, it is shared between all instances. This means that it gets overwritten each time you create a new instance.
Just remove static from both your fields, and your program should work fine.
I have situation. I have to create a Sports Club system in JAVA. There should be a class your for keeping track of club name, president name and braches the club has. For each sports branch also there should be a class for keeping track of a list of players. Also each player should have a name, number, position and salary.
So, I come up with this. Three seperate classes:
public class Team
{
String clubName;
String preName;
Branch []branches;
}
public class Branch
{
Player[] players;
}
public class Player
{
String name;
String pos;
int salary;
int number;
}
The problems are creating Branch[] in another class and same for the Player[]. Is there any simplier thing to do this? For example, I want to add info for only the club name, president name and branches of the club, in this situation, won't i have to enter players,names,salaries etc. since they are nested in each other. I hope i could be clear. For further questions you can ask.
Here's a more complete, formal example of your scenario using conventional Accessors/Mutators (getters/setters), constructors, and Lists. The main() method below illustrates how to use your classes.
public class SportsClub
{
public static void main(String[] args)
{
//Create a team without any branches
Team myTeam = new Team("Southpaws", "South");
//Create a new Branch without any players
Branch myBranch = new Branch();
//Add myBranch to myTeam
myTeam.getBranches().add(myBranch);
//Create a new player
Player myPlayer = new Player("Bob", "Center", 120, 3);
//Add myPlayer to myBranch (and therefore myTeam)
myBranch.getPlayers().add(player);
}
}
public class Team
{
private String clubName;
private String preName;
private List<Branch> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<Branch>();
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public List<Branch> getBranches() { return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(List<Branch> branches) { this.branches = branches; }
}
public class Branch
{
private List<Player> players = new ArrayList<Player>();
public Branch() {}
public List<Player> getPlayers() { return players; }
public void setPlayers(List<Player> players) { this.players = players; }
}
public class Player
{
private String name;
private String pos;
private Integer salary;
private Integer number;
public Player(String name, String pos, Integer salary, Integer number)
{
this.name = name;
this.pos = pos;
this.salary = salary;
this.number = number;
}
public String getName() { return name; }
public String getPos() { return pos; }
public Integer getSalary() { return salary; }
public Integer getNumber() { return number; }
public void setName(String name) { this.name = name; }
public void setPos(String pos) { this.pos = pos; }
public void setSalary(Integer salary) { this.salary = salary; }
public void setNumber(Integer number) { this.number = number; }
}
To answer your question, yes, you can create these objects without populating the Lists with players. The SportsClub.main() above illustrates that.
I would use a List rather than an array since they're (easily) dynamically resizable, but otherwise, you're on the right track.
Think about encapsulation and visibility too. Make all those fields private and provide accessors.
You could create an empty Branch[] array (or better yet - a list) at initialization and add to it later, that way you don't have to enter all the information upon creation - same goes for Player[].
Something like:
public class Team
{
String clubName;
String preName;
private List<Branch> branches;
public Team (String club, String pre) {
clubName = club;
preName = pre;
branches = new LinkedList<Branch>();
}
public void addBranch (Branch branch) {..}
}
public class Branch
{
private List<Player> players;
public Branch () {
players = new LinkedList<Player>();
}
public void addPlayer (Player player) {..}
}
public class Player
{
String name;
String pos;
int salary;
int number;
}
I think that's good. You should probably have methods in the classes to manage your information though--don't try to do anything serious from "Outside" these classes.
to be more specific: All your members should be private and only used/accessed from within the classes--also in general avoid setters and getters, instead ask the class to do things for you.
For example, if you wanted to know how many players were in a branch, you would call branch.countPlayers, not access the Player array to count the players from outside.
If you wanted to know how many players were in a team, you would call team.countPlayers which would call branch.countPlayers for each Branch, sum them up and return the value.
If you wanted to see which branch a player was in, you would call Team.findPlayer(playerName). Team would call branch.hasPlayer(playerName) on each branch until it returned a true, then Team would return the Branch object that returned true.
etc.
Note that this resolves your "Populated or not" issue. If you simply have methods like "hasBranch()", "addBranch()", "removeBranch()" then it doesn't matter how or when you populate the branches array since you control it all within the Team class you can change it's implementation at any time and not change a single line outside that class.
You won't have to enter anything into the players array, nor the branch[]. Provided you make the fields accessible, of have properties, you will be able to put them in however you like.
The class structure looks good to me, but a List would be better so that you don't have to worry about resizing arrays down the road.
Nothing wrong with your classes. I personally would use a strongly-typed List to store the branches and players:
public class Team
{
String clubName;
String preName;
List<Branch> branches;
}
public class Branch
{
List<Player> players;
}
Not sure of the requirement, but you'd probably want to have some kind of identifier or name for each Branch, right?
There's nothing in these classes that forces you to create new players just to instantiate a Branch. The list of Players can remain null or empty until you need them.