I'm making a pokemon game for fun and I want to be able to reduce the HP of the two pokemon fighting. What i'm doing is calling a method inside an 'if statement',which is inside of a loop, an have Java call a method from another class to reduce the HP.
Below is the Code as I have it...
import java.util.Scanner;
public class gameTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inputSystem = new Scanner(System.in);
Scanner playerName = inputSystem;
System.out.println("Hello Player please type in the name of your pokemon.");
pokemon playerOne = new pokemon(playerName.nextLine());
pokemon playerTwo = new pokemon();
System.out.println(playerOne.toString());//shows player pokemon
System.out.println(playerTwo.toString());//shows enemy pokemon
System.out.println("Let's Battle! What do you do?");
while (playerOne.getHealthPoints() >= 0 || playerTwo.getHealthPoints() >= 0){
System.out.println("1. Bite 2. Slash 3. Flee");
int userChoice = inputSystem.nextInt();
if (userChoice == 3){
break;
}
else if (userChoice == 1 || userChoice == 2){
//playerTwo.getHealthPoints()
}
}
}
}
Also like I said above i'm calling a method from another class..
public class pokemon {
private String pokemonSpecies;
private String nameOfpokemon;
private int attackDamage;
private int healthPoints;
public pokemon (){
nameOfpokemon = "Enemy";
attackDamage = 1;
healthPoints = 3;
}
public pokemon (String desiredName){
nameOfpokemon = desiredName;
attackDamage = 1;
healthPoints = 3;
}
public String getPokemonSpecies() {
return pokemonSpecies;
}
public void setPokemonSpecies(String pokemonSpecies) {
this.pokemonSpecies = pokemonSpecies;
}
public String getNameOfpokemon() {
return nameOfpokemon;
}
public void setNameOfpokemon(String nameOfpokemon) {
this.nameOfpokemon = nameOfpokemon;
}
public int getAttackDamage() {
return attackDamage;
}
public void setAttackDamage(int attackDamage) {
this.attackDamage = attackDamage;
}
public int getHealthPoints() {
return healthPoints;
}
public void setHealthPoints() {
this.healthPoints = healthPoints;
}
#Override
public String toString(){
return "Name of Pokemon: " + nameOfpokemon + " Attack Damage: " + attackDamage + " Health Points: " + healthPoints;
}
public int enemyDamage(int damage){
setHealthPoints() = getAttackDamage() - getHealthPoints();
}
}
The last bit about public in enemyDamage(...) is where I'm stuck. I don't know if I should send an integer that can reduce the HP. Or is I should use this method to call other methods...
Any advice?
First use can change your setHealthPoints() method to
public void setHealthPoints(int healthPoints) {
this.healthPoints = healthPoints;
}
Here I assume
damage = attack/damage done by opponent's pokemon.
getHealthPoints() = my pokemon's health.
Then enemyDamage() goes in this way.
public void enemyDamage(int damage){
setHealthPoints(getHealthPoints() - damage);
}
Related
So I am currently learning about interfaces within java and in this program I created 3 separate classes Building.class, Bicycle.class, and Car.class and they are unrelated but they all use the CarbonFootPrint Interface. in my processCarbonFootPrintData class I created an arrayList that holds the data from my objects then I loop through the array list and I get this weird output that does not show the result of my input data.
package CarbonFootPrintPackage;
import java.util.Scanner;
/**
*
* #author cjt1496
*/
public class Building implements CarbonFootPrintInterface {
private int numberOfFloors;
private int numberOfJanitors;
private boolean isBuildingOpenOrClosed;
double naturalGasConsumed;
Scanner input = new Scanner(System.in);
public double getNaturalGasConsumed() {
return naturalGasConsumed;
}
public void setNaturalGasConsumed(double naturalGasConsumed) {
this.naturalGasConsumed = naturalGasConsumed;
}
public int getNumberOfFloors() {
return numberOfFloors;
}
public void setNumberOfFloors(int numberOfFloors) {
this.numberOfFloors = numberOfFloors;
}
public int getNumberOfJanitors() {
return numberOfJanitors;
}
public void setNumberOfJanitors(int numberOfJanitors) {
this.numberOfJanitors = numberOfJanitors;
}
public boolean isIsBuildingOpenOrClosed() {
return isBuildingOpenOrClosed;
}
public void setIsBuildingOpenOrClosed(boolean isBuildingOpenOrClosed) {
this.isBuildingOpenOrClosed = isBuildingOpenOrClosed;
}
public Building(){
}
public Building(int numberOfFloors, int numberOfJanitors, boolean isBuildingOpenOrClosed, double naturalGasConsumed) {
this.numberOfFloors = numberOfFloors;
this.numberOfJanitors = numberOfJanitors;
this.isBuildingOpenOrClosed = isBuildingOpenOrClosed;
this.naturalGasConsumed = naturalGasConsumed;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for a Building ");
System.out.println("--------------------------------------------------------");
System.out.println("How many therms of natural gas has your building consumed?");
naturalGasConsumed = input.nextDouble();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this building is " +
(getNaturalGasConsumed() * 11.7) + "pounds of CO2 from natural gas use.\n");
}
}
START OF CAR.CLASS
public class Car implements CarbonFootPrintInterface {
private int numberOfSeats;
private int steeringWheel;
double emissionConversionFactor;
double distanceTraveled;
int numberOfTimesTraveled;
Scanner input = new Scanner(System.in);
public int getNumberOfSeats() {
return numberOfSeats;
}
public void setNumberOfSeats(int numberOfSeats) {
this.numberOfSeats = numberOfSeats;
}
public int getSteeringWheel() {
return steeringWheel;
}
public void setSteeringWheel(int steeringWheel) {
this.steeringWheel = steeringWheel;
}
public double getEmissionConversionFactor() {
return emissionConversionFactor;
}
public void setEmissionConversionFactor(double emissionConversionFactor) {
this.emissionConversionFactor = emissionConversionFactor;
}
public double getDistanceTraveled() {
return distanceTraveled;
}
public void setDistanceTraveled(double distanceTraveled) {
this.distanceTraveled = distanceTraveled;
}
public int getNumberOfTimesTraveled() {
return numberOfTimesTraveled;
}
public void setNumberOfTimesTraveled(int numberOfTimesTraveled) {
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public Car(){
}
public Car(int numberOfSeats, int steeringWheel, double emissionConversionFactor, double distanceTraveled, int numberOfTimesTraveled) {
this.numberOfSeats = numberOfSeats;
this.steeringWheel = steeringWheel;
this.emissionConversionFactor = emissionConversionFactor;
this.distanceTraveled = distanceTraveled;
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for a Car ");
System.out.println("--------------------------------------------------------");
System.out.println("Enter your emissionConversionFactor (Must be a decimal)");
emissionConversionFactor = input.nextDouble();
System.out.println("Enter your distance traveled in km (Must be a decimal)");
distanceTraveled = input.nextDouble();
System.out.println("Enter the number of times you traveled to your destination");
numberOfTimesTraveled = input.nextInt();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this bicycle is " +
getEmissionConversionFactor() * (getDistanceTraveled() * getNumberOfTimesTraveled()) +"Kg CO2e\n");
}
}
START OF BICYCLE.CLASS
import java.util.Scanner;
public class Bicycle implements CarbonFootPrintInterface {
private int handleBars;
private boolean KickStand;
double emissionConversionFactor;
double distanceTraveled;
int numberOfTimesTraveled;
Scanner input = new Scanner(System.in);
public int getHandleBars() {
return handleBars;
}
public void setHandleBars(int handleBars) {
this.handleBars = handleBars;
}
public boolean isKickStand() {
return KickStand;
}
public void setKickStand(boolean KickStand) {
this.KickStand = KickStand;
}
public double getEmissionConversionFactor() {
return emissionConversionFactor;
}
public void setEmissionConversionFactor(double emissionConversionFactor) {
this.emissionConversionFactor = emissionConversionFactor;
}
public double getDistanceTraveled() {
return distanceTraveled;
}
public void setDistanceTraveled(double distanceTraveled) {
this.distanceTraveled = distanceTraveled;
}
public int getNumberOfTimesTraveled() {
return numberOfTimesTraveled;
}
public void setNumberOfTimesTraveled(int numberOfTimesTraveled) {
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public Bicycle(){
}
public Bicycle(int handleBars, boolean KickStand, double emissionConversionFactor, double distanceTraveled, int numberOfTimesTraveled) {
this.handleBars = handleBars;
this.KickStand = KickStand;
this.emissionConversionFactor = emissionConversionFactor;
this.distanceTraveled = distanceTraveled;
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for Bicycle ");
System.out.println("--------------------------------------------------------");
System.out.println("Enter your emissionConversionFactor (Must be a decimal)");
emissionConversionFactor = input.nextDouble();
System.out.println("Enter your distance traveled in km (Must be a decimal)");
distanceTraveled = input.nextDouble();
System.out.println("Enter the number of times you traveled to your destination");
numberOfTimesTraveled = input.nextInt();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this bicycle is " +
getEmissionConversionFactor() * (getDistanceTraveled() * getNumberOfTimesTraveled()) +"Kg CO2e\n");
}
START Of PROCESS_CARBON_FOOTPRINT_DATA CLASS
public class ProcessCarbonFootPrintData {
public void createCarbonFootPrint(){
Building newBuilding = new Building();
Car newCar = new Car();
Bicycle newBicycle = new Bicycle();
newBuilding.calculateCarbonFootPrint();
newCar.calculateCarbonFootPrint();
newBicycle.calculateCarbonFootPrint();
ArrayList footPrint = new ArrayList();
footPrint.add(newBuilding);
footPrint.add(newCar);
footPrint.add(newBicycle);
for (Object footPrint1 : footPrint) {
System.out.println(footPrint1.toString());
}
}
}
This is the output I am getting:
CarbonFootPrintPackage.Building#42a57993
CarbonFootPrintPackage.Car#75b84c92
CarbonFootPrintPackage.Bicycle#6bc7c054
ArrayList footPrint = new ArrayList();
footPrint.add(newBuilding);
footPrint.add(newCar);
footPrint.add(newBicycle);
for (Object footPrint1 : footPrint) {
System.out.println(footPrint1.toString());
}
Your arraylist contains Objects, it doesn't know anything further of the type. When you do:
for ( Object footPrint1 : footPrint) {
}
You also declare the elements to be of type Object.
There are two things you need to do:
Be specific about the type. If you want to keep your List as is, with the different types, change your loop to:
for ( Object footPrint1 : footPrint) {
if ( footPrint1 instanceof Car )
System.out.println((Car)footPrint1);
else if ( footPrint1 instanceof Building )
System.out.println((Building)footPrint1);
else System.out.println((Bicycle)footPrint1);
}
This way, it'll know what type of data to print.
By just doing that, you'll still run into the same issue, because you haven't overridden your toString methods.
Add the following to your Car class:
#Override
public String toString() {
return "I am a car!!";
}
and you'll see that for the Car instance, that line is printed, instead of the memory address.
Override that method for all your classes, and alter the value returned by it the way you want it to be.
I have an application that I have been working on for a little while, I understand a little of Java.
The scope of the application is combine multiple design patterns in a way that allows reusability, which code can be edited without having to scroll through hundreds of lines of code.
I have implemented a true Singleton Player class.
I have also implemented a decorator weapon class.
I am not looking to add a state pattern for the player class, an example of this would be AliveState and DeadState. Something simple so I understand the workings of it all.
For the sake of this I will post the full PlayerSingleton class:
public class PlayerSingleton{
private static PlayerSingleton player;
Scanner scanner = new Scanner(System.in);
private String playerName;
private Integer playerHealth;
private Weapon weapon;
private PlayerSingleton(Weapon weapon, String pName, int pHealth) {
this.weapon = weapon;
playerName = pName;
playerHealth = pHealth;
}
public static Weapon chooseWeapon(String choice) {
switch (choice) {
case "MP5":
System.out.println("You have chosen MP5!");
return new MP5Weapon();
case "SNIPER":
System.out.println("You have chosen Sniper!");
return new SniperRifleWeapon();
case "SHOTGUN":
System.out.println("You have chosen Shotgun!");
return new ShotgunWeapon();
default:
System.out.println("No gun by that name found!");
return null;
}
}
public static PlayerSingleton getInstance(String choice, String name, int health) {
System.out.println("Choose Weapon to play the with: ");
Weapon weapon = PlayerSingleton.chooseWeapon(choice);
weapon.getDescription();
if (player == null) {
player = new PlayerSingleton(weapon, name, health);
}
return player;
}
public void getWeaponDamage(Weapon damage) {
System.out.println("Damage of weapon: " + weapon.damage());
}
public void attackState(double damage) {
damage = player.weapon.damage();
}
// #Override
// public void aliveState() {
// if(playerHealth >= 1){
//
// }
// }
// #Override
// public void deadState() {
// if(playerHealth ==0){
// System.out.println("You are dead");
// System.out.println("GameOver");
// }
// }
public void chosenWeapon() {
System.out.println("Player Info: " + playerName + " " + "Has: " + playerHealth + " health");
System.out.println(weapon.getDescription() + ":" + " base damage: " + weapon.damage());
}
public void addBasicAttachment(String attachment) {
switch (attachment) {
case "SIGHT":
weapon = new BasicSight(weapon);
break;
case "SILENCER":
weapon = new BasicSilencer(weapon);
break;
case "STOCK":
weapon = new BasicStock(weapon);
break;
default:
System.out.println("No Attachment found!");
}
}
I've tried to implement this with help of Head first design patterns (State) but using the Singleton Pattern on the player class means that I cannot call the object from another class.
public class DeadState implements PlayerState{
PlayerSingleton player;
public DeadState(PlayerSingleton player){
this.player = player;
}
#Override
public void deadState() {
System.out.println("You are Dead!");
}
#Override
public void aliveState() {
System.out.println("You are Dead!");
}
}
Above is a test on making a DeadState implementing from a PlayerState interface.
Is there any way to do this with separate classes using the state pattern with PlayerSingleton?
Seriously any help would be amazing!
Also if you could explain the answer so I understand better.
First of all about this sentence that you said:
using the Singleton Pattern on the player class means that I cannot call the object from another class.
Actually you can call the object from other classes, as long as you have access to the instance, and that's how state pattern works.
I took your classes and remove some code just for the sake of simplicity and explain better the solution, you can add back the parts of the code I removed if you use this solution:
I used the two states you have in your code, first this is the PlayerState interface, it has two methods, one for taking damage and other for respawning:
public interface PlayerState {
void respawn();
void takeDamage(int damage);
}
Then the implementation of Alive state has only implementation for the takeDamage method, which receives the amount of damage taken:
public class AliveState implements PlayerState {
private PlayerSingleton player;
public AliveState(PlayerSingleton player) {
this.player = player;
this.player.setHealth(PlayerSingleton.MAX_PLAYER_HEALTH);
}
#Override
public void takeDamage(int damage) {
System.out.println(String.format("Suffering %d damage!", damage));
player.setHealth(player.getHealth() - damage);
if (player.getHealth() <= 0) {
player.setLives(player.getLives() - 1);
player.setState(new DeadState(player));
}
}
#Override
public void respawn() {
System.out.println("Nothing to do, player is alive!");
}
}
Same for the implementation of the DeadState, which has only implementation for the respawn method, as long as the player has lives left:
public class DeadState implements PlayerState {
private PlayerSingleton player;
public DeadState(PlayerSingleton player) {
this.player = player;
}
#Override
public void takeDamage(int damage) {
System.out.println("Nothing to do, player is dead!");
}
#Override
public void respawn() {
if (player.getLives() > 0) {
System.out.println("respawning to start location!");
player.setState(new AliveState(player));
} else {
System.out.println("Game Over!");
}
}
}
And finally the PlayerSingleton class, which is assigned the state AliveState when the player is created, the takeDamage and respawn methods call the implementations in the current player's state, and if you noticed, the State implementations have a reference to the player's instance, so they can change the object state.
public class PlayerSingleton {
public static Integer MAX_PLAYER_HEALTH = 500;
public static Integer DEFAULT_PLAYER_LIVES = 2;
private static PlayerSingleton player;
private Integer health = MAX_PLAYER_HEALTH;
private int lives = DEFAULT_PLAYER_LIVES;
private PlayerState playerState;
private PlayerSingleton() {
setState(new AliveState(this));
}
public static PlayerSingleton getInstance() {
if (player == null) {
player = new PlayerSingleton();
}
return player;
}
public void sufferDamage(int damage) {
playerState.takeDamage(damage);
}
public void respawn(String location) {
playerState.respawn();
}
// Getters and Setters
}
I used the following main method to test:
public static void main(String[] args) {
PlayerSingleton playerSingleton = PlayerSingleton.getInstance();
playerSingleton.takeDamage(300);
playerSingleton.respawn();
playerSingleton.takeDamage(300);
playerSingleton.respawn();
playerSingleton.takeDamage(600);
playerSingleton.respawn();
}
And this was the output:
Suffering 300 damage!
Nothing to do, player is alive!
Suffering 300 damage!
Player is dead!
respawning to start location!
Suffering 600 damage!
Player is dead!
Game Over!
I am developing a blackjack game using java but after i got done (or almost done) writing the whole program J grasp says "No main methods, applets or MIDlets found in file." The code is below. How do i make J Grasp find the main method. If you notice any other thing that will keep the code from running, how would I fix those other things as well.
import java.util.*;
public class Blackjack{
private int points;
private int limit;
private Scanner scan;
private boolean firstTime;
private String response;
private int outcomeOfRoll;
//*******reminder to myself: the word void in the next line of code could be incorrect**********
public Blackjack(){
scan = new Scanner (System.in);
}
public void displayPoints(){
System.out.print("Your points: " + points + "/" + limit);
}
public void startGame () {
System.out.print("Enter point limit");
limit=scan.nextInt();
displayPoints();
}
public void Roll (){
Random randomRoll = new Random();
int outcomeOfRoll = randomRoll.nextInt(6)+1;
System.out.print("You rolled a " + outcomeOfRoll);
}
public String askUser (boolean firstTime){
String response = null;
if (firstTime== true){
System.out.print("Start playing?");
response = scan.next();
return response;
}
else {
System.out.print("Keep playing?");
response = scan.next();}
return response;
}
public void displayResult(){
if (points==limit)
System.out.print("Blackjack!");
else if (points>limit)
System.out.print("Bust!");
else if (points<limit)
System.out.print("Stand at " + points + " points!");
}
public void play(){
boolean gameOver = false;
startGame();
askUser(firstTime);
while(response.equals("yes") && gameOver==false){
points = points + outcomeOfRoll;
displayPoints();
if (points>=limit)
gameOver=true;
askUser(firstTime);
displayResult();
}
}
public void main(){
play();
}
}
In Java, you need to have a method named main in at least one class and it has to be public static void and takes an array of String as a parameter.
Main method in Java looks like this:
public static void main(String[] args)
just modify your main method to match it's signature exactly
for more information I suggest you to read documentation
Eclipse keeps informing of an error when I try to implement a counter for a number of instances when called by the constructor. I've been searching on the matter, but the solutions are the exact thing eclipse won't let.
The problem is in Student() { count++; } in the subclass.
Implicit super constructor Dosije() is undefined. Must explicitly invoke another constructor
Main file
import java.util.Scanner;
public class TestDosije {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String jmbg=null;
System.out.println("ime osobe: ");
String ime= in.next();
System.out.println("prezime osobe: ");
String prezime= in.next();
System.out.println("jmbg: ");
while(!(Dosije.jesteJMBG(jmbg =in.next()) )) {
}
String ime_prezime= ime + " " + prezime;
Dosije dosije = new Dosije(ime_prezime, jmbg);
System.out.println(dosije.toString());
System.out.println("broj indeksa: ");
int index= in.nextInt();
System.out.println("godina upisa: ");
int upis= in.nextInt();
System.out.println("studije: ");
int studije= in.nextInt();
Student student = new Student(dosije, index, upis, studije);
System.out.println(student.toString());
System.out.println(student.getCount());
}
}
The superclass
public class Dosije {
private String ime_prezime;
private String jmbg;
public Dosije(String ime_prezime, String jmbg) {
this.ime_prezime=ime_prezime;
this.jmbg=jmbg;
}
public Dosije(final Dosije d) {
ime_prezime=d.ime_prezime;
jmbg=d.jmbg;
}
public String getImePrezime() { return ime_prezime; }
public void setImePrezime(String ime_prezime) { this.ime_prezime= ime_prezime;}
public String getJMBG() { return jmbg; }
public void setJMBG(String jmbg) { this.jmbg= jmbg;}
public String toString() {
return ime_prezime + "\njmbg: " + jmbg;
}
public static boolean jesteJMBG(String jmbg) {
if(jmbg.length() != 13) {
System.err.println("jmbg ima 13 cifara");
return false;
}
for(int i=0;i < jmbg.length(); i++) {
if(!(Character.isDigit(jmbg.charAt(i))) ) {
System.err.println("jmbg nije broj!");
return false;
}
}
return true;
}
}
The subclass of which instances I'm trying to count
public class Student extends Dosije{
private int br_index;
private int god_upis;
private int profil_studija;
private static int count=0;
Student() {
count++; //the devil himself
}
public Student(final Dosije d, int index, int upis, int studije){
super(d);
br_index=index;
god_upis=upis;
profil_studija=studije;
}
public Student(final Student s) {
super(s);
br_index=s.br_index;
god_upis=s.god_upis;
profil_studija=s.profil_studija;
}
public void setProfil(int n) {profil_studija=n;}
public int getCount() { return count; }
public String Studije(int i) {
if(i == 0)
return "Osnovne";
else if(i == 1)
return "MSc";
else
return "PhD";
}
public String toString() {
return super.toString() + "\n" + "broj indeksa: " + br_index + "/" + (god_upis % 100) + "\n"
+ "studije: " + Studije(profil_studija);
}
}
Your Student() constructor doesn't pass compilation since the super class doesn't have a parameterless constructor, so the implicit call to super(); added by the compiler doesn't pass compilation.
You can add a public Dosije() {} constructor to prevent that compilation error.
However, you might want to increment count in the other Student constructors too, in order to count the total number of instances created, regardless of which constructor was used.
pretty much I've made a program that goes a little like this
Players are added to an array
they are then all placed against each other(just like a football match, every team plays every team)
They are then randomized
the program should display the end result(if you win a game you get 3 points) etc..
I keep getting a message from Eclipse saying ".setScore has NOT been coded..
TestGame.java
public class TestGame {
static Players ceri = new Players("Ceri", 0);
static Players harry = new Players("Harry", 0);
static Players matthew = new Players("Matthew", 0);
static Players james = new Players("James",0);
static Players kwok = new Players("Kwok",0);
static Players lewis = new Players("Lewis",0 );
static Game League = new Game();
int Ceri = 0;
public static void main(String[] args) {
League.addPlayers(ceri);
League.addPlayers(matthew);
League.addPlayers(james);
League.addPlayers(kwok);
League.addPlayers(lewis);
League.addPlayers(harry);
League.randomize();
League.Results();
}
}
Game.java
public class Game extends TestGame {
Scanner s = new Scanner(System.in);
private Players[] people = new Players[6];
private int counter = 0;
List<String> Matches = new ArrayList<String>();
public void addPlayers(Players obj){
people[counter] = obj;
counter++;
System.out.println(obj.getName());
}
public String randomize(){
for(int i = 0; i < people.length; i++){
for(int j = i + 1; j < people.length; j++){
if(people[i].equals(people[j].getName())){
continue;
} else {
Matches.add(people[i].getName() + " V " + people[j].getName());
}
}
}
return null;
}
public String Results(){
while(!Matches.isEmpty()){
int Game = (int)(Math.random() * Matches.size());
String Verses = (String)Matches.get(Game);
System.out.println(Verses);
System.out.println("Who has won?");
String name = s.nextLine();
//**ISSUE LIES HERE**
if(Verses.contains(name)){
if(name == "ceri"){
ceri.setScore(3);
} else if(name == "harry"){
harry.setScore(3);
}else if (name == "matthew"){
matthew.setScore(3)
} else if(name == "lewis"){
lewis.setScore(3)
}else if ( name == "james"){
james.setScore(3)
}else if(name == "kwok"){
kwok.setScore(3);
}
}
Matches.remove(Game);
System.out.println(one);
return null;
}
return null;
}
}
WHERE ECLIPSE SAYS .setScore ISNT.
Players.java
public class Players {
private String name;
private int score;
public Players(String name, int score){
this.name = name;
this.score = score;
}
public String getName(){
return this.name;
}
public int getScore() {
return this.score;
}
public void setScore(int score) {
this.score =+ score;
}
}
All the players are static members of TestGame class. They can access only static methods of Players now. So that is why you are getting the error.
First off, there are compile errors. Please see merlin2011's answer for reference.
As to your actual issue, your Players (ceri, harry, matthew, etc.) are static members of TestGame...but are not publicly exposed. This means that other objects can't see them, and so can't access them. Add the public keyword to them:
public class TestGame {
public static Players ceri = new Players("Ceri", 0);
public static Players harry = new Players("Harry", 0);
public static Players matthew = new Players("Matthew", 0);
public static Players james = new Players("James",0);
public static Players kwok = new Players("Kwok",0);
public static Players lewis = new Players("Lewis",0 );
...
}
Now that they are publicly exposed, you need to reference them correctly. Your Game class doesn't know what ceri is when you call setScore(3), Since it is not a member of that class. Instead, you need to tell it where ceri is located; in your TestGame class. For reference, I've also used the traditional string equality comparison function.
if(name.equals("ceri")){
TestGame.ceri.setScore(3);
}
Use this format for the other IF statements you have.
Your code has a couple of issues, but neither of them is related to setScore not being defined.
You are missing semicolons in the following block.
if(Verses.contains(name)){
if(name == "ceri"){
ceri.setScore(3);
} else if(name == "harry"){
harry.setScore(3);
}else if (name == "matthew"){
matthew.setScore(3)
} else if(name == "lewis"){
lewis.setScore(3)
}else if ( name == "james"){
james.setScore(3)
}else if(name == "kwok"){
kwok.setScore(3);
}
}
You are not using equals for String comparison in the block above.
Here is a corrected version:
if(Verses.contains(name)){
if(name.equals("ceri")){
ceri.setScore(3);
} else if(name.equals("harry")){
harry.setScore(3);
} else if (name.equals("matthew")){
matthew.setScore(3);
} else if(name.equals("lewis")){
lewis.setScore(3);
} else if ( name.equals("james")){
james.setScore(3);
} else if(name.equals("kwok")){
kwok.setScore(3);
}
}