The assignment question was define a Constructor for class player, it asks to input the players name (which I think I've done correctly), and initialise the position to zero as well to create a players jar by using new Jar();
So I created 2 classes one called Jar and one called Player, basically a players Jar Position is meant to be 0 and a players Stone is meant to be null. (Player position and Jar position are different)
public class Jar
{
public static int position;
public static Jar stone;
/**
* Constructor for objects of class Jar
*/
public Jar()
{
this.position = 0;
this.stone = null;
}
}
import java.util.Scanner;
public class Player
{
// instance variables - replace the example below with your own
private String name ;
private int position;
private Player JarPosition;
private Player JarStone;
/**
* Constructor for objects of class Player
*/
public Player()
{
System.out.print("Enter player's name: ");
name = Global.keyboard.nextLine();
this.position = 0;
Jar jar = new Jar();
JarPosition = jar.position;
JarStone = jar.stone;
lets go through it step by step.
First you start your program with a main method:
public static void main(String[] args){
// execute this code here
}
This method you can put in any class you like, though I would suggest to put it in a class that you will use to "control" your program's flow:
public class MyJarProgram{
public static void main(String[] args){
}
}
Now to get rid of all that static and non-static confusion, let's keep with "Objects" (instances of classes). Meaning this main method is the only static thing you will need.
Now you want to start constructing your players, the jar (I don't really know what that is but nevermind :) and positions and everything, so you might want to start asking the user for the players name:
public static void main(String[] args){
System.out.print("Please enter the player's name");
String playerName = Global.keyboard.nextLine(); // I guess this method works like this, so your variable playerName should now contain the user's input
// now you can instantiate your player object
Player player = new Player(playerName); // here we need a constructor of the class player that takes the name.
}
So now you have to create your Player class and give it the constructor with the name
public class Player{
private String name; // make all variables in your classes non-static and private to be on the save-side
public Player(String name){
this.name = name; // you take the parameter name and set the private member variable name to the same value
}
// since your variable name is private to the class player you might want to add some standard getter and setter methods like this:
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
As you did it with the name of the player, you could do it with the position as well. Give the Player class another member variable position and add the necessary code to the constructor (and maybe the getter and setters too).
Then your main method could look like this:
public static void main(String[] args){
System.out.print("Please enter the player's name");
String playerName = Global.keyboard.nextLine();
Player player = new Player(playerName, 0); // creates the player with his name and position.
System.out.println("Player :"+player.getName()+" is on position "+player.getPosition()); // and that's how you can access the players attributes with your getters and setters
}
Although I guess you might want to give the player by default position 0, in which case you don't pass the position in the constructor but set the position to 0:
public Player(String name){
this.name = name; // takes the parameter to init the name
this.position = 0; // will initialize the position by default with 0
}
Well I hope this helps you get a better idea on constructors and classes and stuff. Good luck!
Related
I am having a hard time understanding the object oriented world. I am working on a homework assignment and I can't understand why I am getting an error here. The issue I am having is in the add method. I am using the Netbeans IDE (per professor requirement) and the problem I am getting is in the add method. There are two errors that both say "Cannot find Symbol"; one is in reference to the variable customers while the other is in reference to the variable numCustomer. I am trying to understand what I am doing wrong, not just how to fix it.
What I have so far:
package homework6;
/**
*
* #author christian
*/
public class Homework6 {
// Declare variables
private int numCustomers = 0;
private Customer customer;
// Constructor
public Homework6() {
Customer[] customers = new Customer[50];
}
/**
* #param args the command line arguments
*/
public void main(String[] args) {
System.out.println("Christian Beckman N00963294");
System.out.println("Homework 6");
System.out.println(); // Prints a blank line
// Create and instance of Homework6
Homework6 homework6 = new Homework6();
homework6.execute(args);
}
private void add(Customer customer) {
int i = 0;
customers[i] = customer;
i++;
numCustomer++;
}
private void displayCustomers() {
}
private void execute(String[] args) {
}
private int getTotal() {
}
private void readFile(String filename) {
}
}
Your variable is numCustomers with an 's' but your method refers to numCustomer++; without an 's'.
It should be:
numCustomers++;
For
private Customer customer;
it should probably be:
private Customer[] customers;
Be very careful in your code where you refer to customer and customers. It looks like you are using the convention "customer" for just one and "customers" for the array. If that is too subtle for you then consider changing to something like oneCustomer and allCustomers.
You create an array of Customer objects in the constructor, then the array is immediately destroyed. Try declaring it like this:
public class Homework6 {
// Declare variables
private int numCustomers = 0;
private int i = 0;
private Customer customer;
private Customer[] customers;
// Constructor
public Homework6() {
customers = new Customer[50];
}
...
The reason for this, is any variables declared inside a method (in this case, the constructor) has something called local scope which means it can ONLY be accessed inside that method. The variables you declare outside the methods have something called global scope, which means that variable can be accessed across all the methods in a class.
For the same reason as above, i will keep resetting to 0 each time you call the add function. To fix that, declare private int i = 0 above the constructor with the other variables. Then write the method like so:
private void add(Customer customer) {
customers[i] = customer;
i++;
numCustomers++;
}
Also, whenever you do numCustomer++ in the add method, you should put numCustomers++ like above because you declared numCustomers with an 's' at the end. Has to match EXACTLY.
I am never quite sure that I am using static methods correctly. I understand how they work.
Let's say I have this class called Player(Java):
private int money;
private int lot;
private String piece;
private int playerNum;
public Player(String _piece, int _playerNum)
{
piece = _piece;
lot = 0;
playerNum = _playerNum;
money = 20000;
}
public int getMoney()
{
return money;
}
public int getLot()
{
return lot;
}
public String getPiece()
{
return piece;
}
There are some other methods + setters, but they are specific to the player object I create, now let's say I have a static method like this:
private static int numOfPlayers;
public static int numPlayers()
{
return numOfPlayers;
}
Where should this numOfPlayers method be placed?
Should it be put in my Player class? And should I increment the numOfPlayers varible everytime a new isntance of the player object is created?(via the constructor)
Or, should I have I have the method in my Game class as non-static and just call the method everytime I create a new Player.
Static fields and methods are supposed to represent stateless attributes of a class; i.e. not pertinent to a particular object.
But be careful with multithreading with statics since the whole class has to be locked rather than just one object. This can lead to concurrency bottlenecks.
As for your numOfPlayers, you'll probably end up having a collection of players developed somewhere else, in which case that function will be a method on that collection not in the player class.
Ideally, in my opinion at least, an individual player should not really be concerned about the players collection. Therefore a static function such as the one you propose would not be good design.
It is a matter of design, which obviously includes a lot of personal preference.
You really should have a look at the factory design pattern, which is a good way of handling such cases. Here, you could have a
public class PlayerFactory {
private int numPlayers = 0;
public int getNumPlayers() { ... }
public Player makeNewPlayer(...) { ... }
}
that takes care of A) incrementing the player count appropriately.
Depending on your exact use case and code style, you may prefer one variation or another. But it is good to know these patterns and recognize them. And document them. By calling a class SomethingFactory you do hint for other developers that this class follows the factory pattern, for example.
Note that I did not need to use static in above example, assuming that the factory may only be instantiated once. It is common to see the constructor private and instead the class then has a public static final instance only.
You could also call this class Game or Players...
how about you have a List of Players in your game and the number of players is the size of the List.
When you think you should use static for some functionality, don't do it!
Just play along the old rule to never use anything static until you are old and wise and where you perhaps can use it for some very special corner case.
You can create it like this:
Have class Player like you have
Create class Players
class Players
{
private List<Player> players = new List<Players>;
public void AddPlayer(Player pl)
{
this.players.add(pl);
}
public int GetPlayersCount()
{
return this.players.size();
}
}
If you want, you can make this class "static" using Singleton. But try to avoid static classes.
class Players
{
private List<Player> players = new List<Players>;
private static Players instance;
private Players () {};
public static Players getInstance()
{
if (instance == null)
{
instance = new Players ();
}
return instance;
}
public void AddPlayer(Player pl)
{
this.players.add(pl);
}
public int GetPlayersCount()
{
return this.players.size();
}
}
And use it like this
Players players = Players.getInstance();
players.AddPlayer(....)
I would have the list of Players in another class, e.g. Game as you suggested.
Something like
class Game {
private final List<Player> players = new ArrayList<Player>();
public int getNumOfPlayers() {
return players.size();
}
public void addPlayer(final Player player) {
players.add(player);
}
...
You add a player via your instance of Game, game via game.addPlayer(newPlayer), and get the number of players via game.getNumOfPlayers().
The List of players is dynamically allocated.
As for static or not static, I prefer here the non static version, as the players are part of a Game, and one could consider they may be several games - and players would be part of an instance of Game.
Basically I have to write a simple contact manager, and store objects in array list.
What frustrates me is that I have newContact method, which when called creates new instance of Contact, and stores it in ArrayList. The problem is that every time I call that method, all other objets in the list gets overwritten.
import java.util.ArrayList;
public class ContactManager {
public static ArrayList<Contact> contactList = new ArrayList<Contact>();
public static Contact[]c = {};
public static void main(String[]args){
newContact();
newContact();
System.out.println(contactList.get(1).getName());
System.out.println(contactList.get(0).getName());
}
public static void newContact(){
Contact c = new Contact();
contactList.add(c);
}
}
In Contact class constructore there is code that initializes the object's properties using Scanner class.
If in first call I Enter "John" and in second function call I enter "Peter", the above code will print out:
Peter
Peter.
Why doesn't it prints out John Peter?
Only thing I can think of is that maybe Java stores only reference to object in arraylist, and that unlike variables objects don't get destroyed after function executes..
Any ways around this?
I hope this explains what I am trying to achieve.
PS. I know people hate people that as homework questions. But I am doing this as an extra, in order to learn new stuff. Original assignment barely asks to instantiate 5 objects and store them in ArrayList. And I have that done, now I am just trying to see if I could come up with more dynamic solution.
Contact class code:
import java.util.Scanner;
public class Contact{
private static String name, number;
//constructor will ask to enter contact details
public Contact(){
Scanner in = new Scanner(System.in);
System.out.println("Enter name:");
name = in.next();
System.out.println("Enter number:");
number = in.next();
}
//getters and setters
public static String getName(){
return name;
}
public static String getNumber(){
return number;
}
public static void setName(String newName){
name = newName;
}
public static void setNumber(String newNumber){
number = newNumber;
}
}
It's because the members in the Contact class are static. That means that all Contact instances share the same name and number. You should make them instance members so that each time you do new Contact you get a new copy of these variables.
For example, there is a class Warrior which have linked class Sword. In class Sword defined field: public static int hp = 100; which shows the health points consumed by this type of weapon. There is need for a few classes Warrior. I think I need to define in class Warrior the link Sword (only once) to be able to get static field hp. How can I link it properly?
class public Warrior{
public String name;
public Sword s = new Sword(); // ???
}
class public Sword{
public static int hp = 100;
}
Will new Sword() create link to class each time new Warrior created?
Can I define Sword class as static inside another Weapon class? (There is a need for multiple classes like Sword)
Is following structure correct? Can outer class be static and hold inside another static?
class public Warrior{
public String name;
public int SwordHp = Weapon.Sword().hp;
public int BowHp = Weapon.Sword().hp;
}
(abstract?) public static class Weapon{
public static class Sword{
public static int hp = 100;
}
public static class Bow{
public static int hp = 90;
}
Yes, every time you will get a new Sword.
But, because hp is a static field, you will only get one of those.
Take a look at this link for more information:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
I'm not sure what you exactly want, but as your code example is now, the construction of a Warrior causes the construction of a Sword.
It depends on what you mean by "health points consumed by". If you want to keep track of all the damage this type of weapon has caused, you are good with your static HP field. If this is what you want, I would recommend using a system that keeps track of all sort of statistics. Something like this:
Statistics.getStatisticsForPlayer(playerName). // Get the statistics for a player
increaseValue("damage_caused_by_sword", extraDamage); // increase that property
If you want to keep track of the health points per sword (which looks the most realistic to me, because a Sword isn't sharp forever), you should create the field non-static. This makes the field a property of every Sword instance.
For getting Static field hp you do not need to create
public Sword s = new Sword();
In warrior class. Static variables initialize on load. So you can access you hp anywhere without declaring in the specific classes by just using
Sword.hp ;
This do not have any impact on static variables.
Sword s = new Sword()
As i understand you Have a warrior and different weapons as currently Sword.Every weapon has health points hp and Every Warior has its own weapon and health points. If you use static fields then these health points will be shared among all warriors if 50 wariors then all will using just 100 points togather which i expect you do not want so you should use:
class public Warrior{
public String name;
public Sword s = new Sword(); // ???
}
class public Sword{
public int hp = 100;
}
It will create a new sword with 100 health points every time a warrior is created and every warior will consume his own health points. Hope it will help.
If hp is static, you don't need a member Sword at all. You can access that field with Sword.hp.
If the number of weapon types is constant then enum would work well.
enum Weapon {
Sword(100),
Bow(90);
private final int hp;
private Weapon(int hp) {
this.hp = hp;
}
int getHp();
}
public class Warrior {
public String name;
public Weapon weapon = Weapon.Sword;
}
My personal mini project was to learn arrays here, doing a slightly big jump by making an Array of Objects. What I wanted to do was a mini RPG system where I create a class called monster and give it a couple parameters, and create an array of objects of the Monster class. So far I believe I created that Monster class and the Object of Arrays inside the main method class (Exec_Monster) listed below.
It took me a while initially, but I finally got to a point where I can create the array of Monsters and access them inside the Main class. But is there a way for me to create this Array of Objects and access each object from another class (and their individual values)? For Example, I would create a "Battle" class and then I would pull the "Health" value from an object of Monster.
I'm new to Arrays but I have had some experience with classes for the past two weeks here.
Class:
public class Monster
{
public int hp;
public String n;
public Monster(String name,int health){
n=name;
hp=health;
}
public int returnHealth(){
return hp;
}
public String returnName(){
return n;
}
}
Exec_Monster:
public class Exec_Monster{
public static void main(String args[])
{//Define Monsters
Monster[] monsterid=new Monster[]{
new Monster("Goblin",10),
new Monster("Elf", 8),
new Monster("Ant", 3),
new Monster("Worm", 2),
new Monster("Black Widow",6)};
Random chooser;
int chosenmonster=(chooser.nextInt()*5);
//Start
//while (Battle.wonloss==true) {
// Battle.battle();
}
}
You'd need to pass the monsters into the Battle object somehow (or into another object that you pass into the Battle object). You could pass it as an argument to a method, but in an Object Oriented world, if the monsters really belong to a battle, you could pass them in the constructor and make them available in all the methods of the Battle class.
Example:
public class Battle {
private Monster[] monsters;
private boolean wonloss;
public Battle(Monster[] monsters) {
this.monsters = monsters;
}
public boolean isWonloss() {
return wonloss;
}
public void battle() {
// Do something with monsters,
// and then check if there is any life left in the monsters
int totalHp = 0;
for (Monster monster : monsters) {
totalHp += monster.hp;
}
if (totalHp == 0) {
wonloss = false;
}
}
}
The "battle" part of your main method would then look like:
// Start
Battle battle = new Battle(monsterid);
while (battle.isWonloss()) {
battle.battle();
}