Java how to access methods using an instance from another class - java

I'm trying to write a small game to help with my Java skills. I have a class called "Zombie" and "Player" and I created instances of these classes as so:
Zombie zombie = new Zombie(50, "Infected Zombie", "Slash");
Player defaultPlayer = new Player(100, "Default Player");
Next I requested user input for the attack style of the player:
System.out.println("Which attack style would you like to use?");
defaultPlayer.printAttackStyles();
int option = scanner.nextInt();
scanner.nextLine();
switch(option) {
case 0:
System.out.println("You backed out of the fight.");
break;
case 1:
System.out.println("Punching...");
defaultPlayer.attack(1);
break;
case 2:
System.out.println("Kicking...");
defaultPlayer.attack(2);
break;
case 3:
System.out.println("Headbutting...");
defaultPlayer.attack(3);
break;
case 4:
System.out.println("Tackling...");
defaultPlayer.attack(4);
break;
default:
System.out.println("Not a valid attack style");
}
In my "Player" class I have a method called attack which inflicts a certain amount of damage based on attack style:
public int attack(int attackStyle) {
int damage = 0;
switch(attackStyle) {
case 0:
damage = 0;
break;
case 1:
damage = random.nextInt(20) + 1;
zombie.removeHealth(damage);
break;
case 2:
damage = random.nextInt(25) + 1;
zombie.removeHealth(damage);
break;
case 3:
damage = random.nextInt(30) + 1;
zombie.removeHealth(damage);
this.health -= random.nextInt(5) + 1;
break;
case 4:
damage = random.nextInt(45) + 1;
zombie.removeHealth(damage);
this.health -= random.nextInt(10) + 1;
break;
}
return damage;
}
In each case of the attack method, I have a line of code that says
zombie.removeHealth(damage);
Since the instance is only declared in the Main class how can I access that instance in order to access the method removeHealth() in the zombie class? Sorry if this question is simple but I can't figure this out.

In your method attack you need to add 1 more argument which can be used to pass your instance of Zombie class to attack method.
Make your method signature as
public int attack( int attackStyle, Zombie zombie )
Now in switch block when you call defaultPlayer.attack pass the int value as you was passing earlier and instance of your Zombie class like this
defaultPlayer.attack ( your int value, zombie)
This will pass the zombie instance to attack method then you can the same zombie instance there to call your removeHealth(damage) method.
Hope this solve your query.

pass the reference of Zombie in attack method? like this: defaultPlayer.attack(3, zombie ); Now inside attack method, you can use the reference of zombie and invoke methods on it.

Related

Java Dice Game - Choosing who starts a game based on dice roll and taking turns

Prompt: "Write a program to play the pig game against the computer. At each turn, the current player will
roll a pair of dice and accumulates points. The goal is to reach to 100 or more points before your
opponent does. (For the testing purposes use 30 instead of 100 points) If, on any turn, the player
rolls a 1, all the points accumulated for that round are forfeited and the control of the dice
moves to the other player. If the player rolls two 1s in one turn, the player loses all the points
accumulated thus far are forfeited and the control moves to the other player. The player may
voluntarily turn over the control of the dice after each roll. Therefore player must decide to roll
again (be a pig) and risk losing points, or relinquish control of the dice, possibly allowing the
other player to win. Computer is going to flip a coin to choose the first player "
My problem: I got the program to output that either the computer or the player is going first based on a coin flip. However, how would I actually prompt the program to run a method of the person chosen to start first, and then how would I switch between the computer and player at the end of each turn? Btw, I know this code is incomplete, but I hope that my question makes sense.
Code so far:
import java.util.*;
public class NavaiPigGame
{
public static final int POINT = 30;
public static final int FORFEIT_POINTS = 20;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
play(rand,input);
}
// desription of game
public static void description()
{
System.out.println("***********************************************************************************");
System.out.println("Write a program to play the pig game against the computer. At each turn, the current player will");
System.out.println("roll a pair of dice and accumulates points. The goal is to reach to 100 or more points before your");
System.out.println("opponent does. (For the testing purposes use 30 instead of 100 points) If, on any turn, the player");
System.out.println("rolls a 1, all the points accumulated for that round are forfeited and the control of the dice");
System.out.println("moves to the other player. If the player rolls two 1s in one turn, the player loses all the points");
System.out.println("accumulated thus far are forfeited and the control moves to the other player. The player may");
System.out.println("voluntarily turn over the control of the dice after each roll. Therefore player must decide to roll");
System.out.println("again (be a pig) and risk losing points, or relinquish control of the dice, possibly allowing the");
System.out.println("other player to win. Computer is going to flip a coin to choose the first player");
System.out.println("***********************************************************************************");
System.out.println("lets start the fun");
}
//flips a coin and decides who starts the game
public static String flipCoin(Random rand)
{
int coin = rand.nextInt(2);
String comp = "";
switch (coin)
{
case 0: comp = "heads";
break;
case 1: comp = "tails";
break;
}
return comp;
}
public static int rollDice(Random rand)
{
int dice1 = rand.nextInt(6)+1;
int dice2 = rand.nextInt(6)+1;
System.out.println("Dice 1: " +dice1);
System.out.println("Dice 2: " +dice2);
return dice1+dice2;
}
// select a random name of the computer via arrays
public static String nameComputer(Random rand)
{
int name = rand.nextInt(10);
String compName = "";
switch (name)
{
case 0: compName = "Lisa";
break;
case 1: compName = "Kathy";
break;
case 2: compName = "Hali";
break;
case 3: compName = "Jack";
break;
case 4: compName = "Alex";
break;
case 5: compName = "Max";
break;
case 6: compName = "Jill";
break;
case 7: compName = "James";
break;
case 8: compName = "Martha";
break;
case 9: compName = "Lauren";
break;
}
return compName;
}
public static void play(Random rand, Scanner input)
{
int playerScores = 0;
int playerTotal = 0;
int computerScores = 0;
int computerTotal = 0;
boolean gameOver = false
boolean turnOver = false
description();
String compName = nameComputer(rand);
System.out.println("Hi my name is " + compName);
System.out.print("What is your name? ");
String name = input.nextLine();
System.out.println("Hi " + name + ", I am flipping the coin to determine who goes first");
System.out.print("press any key to start the game. ");
input.nextLine();
String flip = flipCoin(rand);
int turn;
if (flip.equals("heads"))
{
turn = 1;
System.out.println("You are going to start the game");
}
else
{
turn = 0;
System.out.println(compName + " is going to start the game");
}
}
}
Create :
A playTurn(int turn) function (1 for the player, 0 for the computer) that handle a play turn (roll dice, calculate point etc.)
A boolean function that check wether there is a winner or not. Example : isWinner(int player) (again, 1 for the player, 0 for the computer)
Use the function a first time in your if() else statment like that :
if (flip.equals("heads"))
{
turn = 1;
System.out.println("You are going to start the game");
playTurn(turn);
}
else
{
turn = 0;
System.out.println(compName + " is going to start the game");
playTurn(turn);
}
Then you can add :
do {
if(turn == 1){
turn = 0;
playTurn(turn);
}else{
turn == 1;
playTurn(turn);
}
while ( !isWinner(1)|| !isWinner(0) );
This is not very well designed, but it should hopefully give you a hint on what to do next.

Interface method issue [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 5 years ago.
I am required to implement an interface as part of my final school assignment for my Java class. The overridden interface is supposed to print a short message describing how a football player celebrates being drafted in the NFL, something like this:
System.out.println("name dances to celebrate his draft");
However my interface is not printing the message when I put it into the methods which allow the user to add a player to their roster. Here is the overridden interface in the program:
//Overridden celebrate method
#Override
public void celebrate(int i, int place){
int randomInteger;
if (place == 0) //Player is offensive
{
randomInteger = random1Thru6();
//players() is a method that contains all the players in the team
//'place' refers to the players location in the array of players on the team
switch (randomInteger)
{
case 1: System.out.println(players(i).get(place) + " dances to celebrate his draft!");
break;
case 2: System.out.println(players(i).get(place) + " cartwheels to celebrate his draft!");
break;
case 3: System.out.println(players(i).get(place) + " throws a party to celebrate his draft!");
break;
case 4: System.out.println(players(i).get(place) + " sings to celebrate his draft!");
break;
case 5: System.out.println(players(i).get(place) + " gets root beer for everyone to celebrate his draft!");
break;
case 6: System.out.println(players(i).get(place) + " gets donuts to celebrate his draft!");
}
}
else if (place == 1) //Player is defensive
{
randomInteger = random1Thru6();
switch (randomInteger)
{
case 1: System.out.println(players(i).get(place) + " dances to celebrate his draft!");
break;
case 2: System.out.println(players(i).get(place) + " cartwheels to celebrate his draft!");
break;
case 3: System.out.println(players(i).get(place) + " throws a party to celebrate his draft!");
break;
case 4: System.out.println(players(i).get(place) + " sings to celebrate his draft!");
break;
case 5: System.out.println(players(i).get(place) + " gets root beer for everyone to celebrate his draft!");
break;
case 6: System.out.println(players(i).get(place) + " gets pizza to celebrate his draft!");
}
}
}
I am supposed to have one different celebratory response for offensive and defensive positions as is shown in the code above.
Here is the referenced random1Thru6() method:
public int random1Thru6() { //used to get a random number from 1 to 6
int randomInteger = (int)Math.random() * 10;
//this is supposed to call the method over and over again until it gives a number from 1-6 but it has been printing 7-9 as well
if (randomInteger > 6)
random1Thru6();
return randomInteger;
}
And here is the players() method:
//holds and prints all the players
public ArrayList<String> players(int i) {
ArrayList<String> returnedList = new ArrayList<>();
// Christian McCaffrey is a Running Back, Corn Elder is a Corner Back for the Carolina Panthers
ArrayList<String> Players1 = new ArrayList<String>();
Players1.add("Christian McCaffrey");
Players1.add("Corn Elder");
//Jake Butt is a Tight End, Brendan Langley is a Corner Back for the Denver Broncos
ArrayList<String> Players2 = new ArrayList<String>();
Players2.add("Jake Butt");
Players2.add("Brendan Langley");
//Ryan Switzer is a Wide Receiver, Taco Charlton is a Defensive End for the Dallas Cowboys
ArrayList<String> Players3 = new ArrayList<String>();
Players3.add("Ryan Switzer");
Players3.add("Taco Charlton");
//Dalvin Cook is a Running Back, Ifeadi Odenigbo is a Defensive Line for the Minnesota Vikings
ArrayList<String> Players4 = new ArrayList<String>();
Players4.add("Dalvin Cook");
Players4.add("Ifeadi Odenigbo");
switch (i)
{
case 1: returnedList.addAll(Players1);
break;
case 2: returnedList.addAll(Players2);
break;
case 3: returnedList.addAll(Players3);
break;
case 4: returnedList.addAll(Players4);
break;
}
return returnedList;
}
Here is how the celebrate() method is called:
for (int l = 0; l < players(i).size(); l++)
{
if (choosePlayer.equalsIgnoreCase(players(i).get(l)))
{
addPlayer(players(i).get(l));
celebrate(i, l);
enterRoster();
}
}
And:
addPlayer(players(i).get(place));
celebrate(i, place);
enterRoster();
addPlayer(int i, int place) is a method that adds the player for team 'i' in the position of 'place' in the team's player array into the ArrayList of the user's roster.
NOTE: I checked what number was being called by random1Thru6() as suggested in a comment and now I understand why it wasn't printing the celebrate message, since I had (int)Math.random() * 10 it was always returning 0 so I changed it to:
double randomDouble = Math.random() * 10;
int randomInteger = (int)randomDouble;
Now it prints the celebrate messages but random1Thru6() is now returning all numbers 1-9, please explain how I can make this method call itself recursively until it will return a number 1-6.
Thank you delephin for your comment!
NOTE: I have accepted delephin's answer shown below, thank you all for the help!
Add to your main class:
static Random r = new Random();
static {
r.setSeed(System.currentTimeMillis());
}
and change your randomizer method to something like this:
public int random1Thru6() {
return r.nextInt(6) + 1;
}
From a quick test, your previous randomizer was returning zeros.

Rock Paper Scissors Game - Efficiency?

I made a Rock Paper Scissors game for my CS class (senior in highschool) and the shell file my teacher gave me noted that I have to put the do while loop in the runner, but I don't see why? My code works, but she said it'd be better to write it in the runner? Why? Also, how can I write it more efficiently? (Note: I'm a total beginner, and prior to taking this class, had no knowledge of coding. Haven't learned recursion yet.)
my code:
import java.util.Random;
import java.util.Scanner;
public class RockPapersScissors {
private String user;
private int computer;
public RockPapersScissors(){
setPlayers(" ");
}
public RockPapersScissors(String s){
setPlayers(s);
}
public void setPlayers(String s){
user=s;
}
public void play(){
Scanner keyboard = new Scanner(System.in);
Random num = new Random();
int numUser = 0;
String playAgain = "";
do{
System.out.print("Rock-Paper-Scissors - pick your weapon[R,P,S] :: ");
user = keyboard.next();
System.out.println("player has "+ user);
switch(user){
case "R": numUser = 0; break;
case "P": numUser = 1; break;
case "S": numUser = 2; break;
case "r": numUser = 0; break;
case "p": numUser = 1; break;
case "s": numUser = 2; break;
default: System.out.println("Please enter a valid choice. Restart game.\n"); continue;
}
computer = num.nextInt(3);
switch(computer){
case 0: System.out.println("computer has R"); break;
case 1: System.out.println("computer has P"); break;
case 2: System.out.println("computer has S"); break;
}
if(numUser == computer){
System.out.println("!Draw Game!");
}else if(numUser == 0){
if(computer == 1){
System.out.println("!Computer Wins <<Paper Covers Rock>>!");
}if(computer == 2){
System.out.println("!Player Wins <<Rock Breaks Scissors>>!");
}
}else if(numUser == 1){
if(computer == 2){
System.out.println("!Computer Wins <<Scissors cuts paper>>!");
}if(computer == 0){
System.out.println("!Player Wins <<Paper Covers Rock>>!");
}
}else if(numUser == 2){
if(computer == 0){
System.out.println("!Computer Wins <<Rock Breaks Scissors>>!");
}if(computer == 1){
System.out.println("!Player Wins <<Scissors cuts paper>>!");
}
}
System.out.print("\nDo you want to play again? ");
playAgain = keyboard.next();
System.out.println("\n");
}while(playAgain.equals("y") || playAgain.equals("yes") || playAgain.equals("Y"));
System.out.println("Goodbye.");
keyboard.close();
}
}
my runner:
public class RPSRunner {
public static void main(String[] args) {
RockPapersScissors test = new RockPapersScissors();
test.play();
}
}
It all depends on the notion of what a "game" is. If a game is assumed to be a single round of RPS, with no keeping of score, then the teacher's prescribed solution would be good.
However, as soon as you need to retain some form of session state between rounds, such as a score, then you would have to make a design decision: Does the runner contain the logic to keep score, or does the game? Typically, one would have the game keep score, and the runner should know as little as possible about the internal logic of the game.
In another case, you may be asked to expand the runner so that you can choose between two different games. The second game might be "Black Jack", in which case you not only need to keep score, but also keep track of which cards have been played. As you can see the, the complexity of the runner can grow needlessly with your teacher's approach.
The teacher should have given you better requirements, or you should have asked.
By the way, this happens all the time in the real world.
I would say that each round of Rock/Paper/Scissors is independent of all the others. I would have written a single method that took in player 1 and 2 values and returned a winner. Get that to work and then put it in the game loop to play over and over again.
There could be a second overloaded version of play() method with an embedded computer player that would randomly choose and call the two-player version.
Perhaps that is what your teacher meant, too. Why not ask them instead of making us read his/her mind? You can learn a lot using the Socratic method.
Don't worry about efficiency; it doesn't matter for such a trivial application. Make it run; make it run correctly; make it run fast.

Unable to have the methods in one class completely run in main method when called by a class that extends first class

first class built. I think my problems lie within this first class. But i am unable to get the statement to print to the main program when method is called. I am new to java came from perl. Ive tried returning values associated with dmg and blk but the complier says they were never intitialized.
import java.util.Random;
/*****************************************************************************
* roll - rolls the dice. *
* getDice1 - returns value of dice one. *
* getDice2 - returns value of dice two. *
* getTotal - returns the sum value of both dice. *
* *
* *
*****************************************************************************/
//global variables for use throughout class.
public class Options {
int dice1;
int dice2;
int dmg;
int blk;
int health = 100;
Random randm = new Random();
public Options() {
roll();
Attack();
Block();
}
public void roll() {
dice1 = randm.nextInt(6)+1;
dice2 = randm.nextInt(6)+1;
}
public int getTotal() {
return dice1 + dice2;
}
//switch statement used to compare the value of the roll to the determined value of attack.
public protected Attack() {
dice1 = randm.nextInt(6)+1;
dice2 = randm.nextInt(6)+1;
getTotal();
int dmg;
switch (getTotal()) {
case 1: dmg = 2;
break;
case 2: dmg = 3;
break;
case 3: dmg = 4;
break;
case 4: dmg = 5;
break;
case 5: dmg = 6;
break;
case 6: dmg = 7;
break;
case 7: dmg = 8;
break;
case 8: dmg = 9;
break;
case 9: dmg = 10;
break;
case 10: dmg = 11;
break;
case 11: dmg = 12;
break;
}
}
// switch statement is used to compare the roll of dice to determine the value of blk.
public protected Block() {
dice1 = randm.nextInt(6)+1;
dice2 = randm.nextInt(6)+1;
getTotal();
int blk;
switch (getTotal()){
case 1: blk = 2;
break;
case 2: blk = 3;
break;
case 3: blk = 4;
break;
case 4: blk = 5;
break;
case 5: blk = 6;
break;
case 6: blk = 7;
break;
case 7: blk = 8;
break;
case 8: blk = 9;
break;
case 9: blk = 10;
break;
case 10: blk = 11;
break;
case 11: blk = 12;
break;
}
}
// determination whether or not the user has lost health or remains at current health.
public void setHealth(){
health = 100;
}
public int getHealth(){
if (dmg >= blk){
System.out.println("The attack hit for" + dmg);
return health - dmg;
}
else if (dmg < blk){
System.out.println("The attack was blocked");
return health;
}
return health;
}
}
then created character class to that i wanted to access the option methods.
public class Character extends Options {
String name;
public Character(String n) {
name = n;
}
public void setHealth(){
}
public int getHealth(){
return health;
}
public int Attack(){
return dmg;
}
public int Block(){
return blk;
}
}
Then final in the main program I dont believe the dice fro om options class are actually rolling a value because the print statements i put in the main are the only thing that print out. I even let it run for a full 30 mins last night without the sleep to just see if the logic kept coming up with more blocks vs attacks. but no dice it didnt complete at any point.
public class Game{
public static void main(String args[]){
//Constructor for the two separate characters.
Character monster = new Character("monster");
Character hero = new Character("hero");
monster.setHealth();
hero.setHealth();
System.out.println("Health has been set to 100.");
while (monster.getHealth() != 0 || hero.getHealth() !=0) {
try{
System.out.println("Monster is set to Attack!");
monster.Attack();
Thread.sleep(500);
System.out.println("Hero attempts to block");
hero.Block();
Thread.sleep(500);
System.out.println("Hero attempts to Attack");
hero.Attack();
Thread.sleep(500);
System.out.println("Monster attempts to Block");
monster.Block();
}
catch(Exception e){
System.out.println(e);
}
}
if (monster.getHealth() == 0) {
System.out.println("Hero defeated the monster!!!!");
}
else if (hero.getHealth() == 0 ){
System.out.println("Monster has defeated hero!!!!");
}
}
}
i had to use thread sleep as a way to make sure i wasnt missing if the lines from the options class were being missed in printing because the main program ran way to fast.
Attack() and Block() need return types and cannot be both public and protected.
There is already a Java class called Character. You should rename your class. In fact, your Character class is superfluous. The name attribute can be stored in the parent class and all the return statements can go in the parent methods.
Because you are overriding the Options Attack() and Block() methods in your Character class, the parent method is not being called; you need to call it using super.Attack() or super.Block(). But again, this child class is superfluous.
You shouldn't be calculating damage/health in the getHealth() method. Accessor methods should only be used for accessing attributes. Use the mutator method (setHealth()) for changing the value of health and doing your calculations.
Your call to getTotal() before your switch statement is unnecessary because you don't save the return value.
You really don't need those sleep calls.
The reason you think Options() is never initialized is because your Character constructor sets the name for your character, but it doesn't call the constructor for Options. So it never is initialized, or more specifically, all the values default to zero. (You'd want to call super();)
However, as #chancea said in a comment, there are actually a lot of errors in your code. Some quick things I'll mention:
-Options seems like you would want the dice to be re-rolled each time you want to Attack or Block, but it will be set just once when the object is created.
-You are calling getters such as hero.Attack() which just returns an int. You don't do anything with this call, you just get the value and then discard it.
-getHealth() is what is doing the damage to your character. It subtracts your character's health from its own attack and defense, with no regard to the opponent's attack or defense.

Cannot make a static reference to the non-static field .... - java eclipse school project [duplicate]

This question already has answers here:
cannot make a static reference to the non-static field
(7 answers)
Closed 9 years ago.
First off let me announce that I am a noob at Java. I am taking Computer Science and I need help with this code. It is a game, but the problem is that my nStones, computerMove and humanMove methods do not work because of some non static field thing. I have asked everyone in my class, my teacher, and now I am trying the internet. I've looked all over stackoverflow I am a noob and some stuff doesn't make sense. Here it is:
import java.util.*;
public class GameforCompSci
{ /*
To win you must take the last variables so when stone count is zero you lose and the other player wins
you see how many are left there for you determine a strategy to get to be the last one to take it
*/
public static boolean endgame = false;
private int winner = 0;
private int nStones;
public static void main(String[] args)
{
nStones = (int)(Math.random() * (51 - 10) + 10);
System.out.println("Welcome to the game!");
System.out.println("Stones: " + nStones);
int whostarts = 0;
whostarts = (int)(Math.random() * (0 - 2) + 2);
if (whostarts == 1)
{
System.out.println("You start.");
while (nStones > 0){
humanMove(nStones);
System.out.println("Stones: " + nStones);
computerMove(nStones);
System.out.println("Stones: " + nStones);
}
}
else
{ System.out.println("Computer starts.");
while (nStones > 0){
computerMove(nStones);
System.out.println("Stones: " + nStones);
humanMove(nStones);
System.out.println("Stones: " + nStones);
}
}
//endgame logic
if (endgame = true)
{
switch(winner){
case 1:
System.out.println("You win!");
break;
case 2:
System.out.println("You lose, computer wins!");
break;
default:
System.out.println("Something went wront please try again!");
}
System.exit(0);
}
}
public int computerMove(int nStones)
{
int picked = 0;
if (nStones <= 0)
{
winner = 1;
endgame = true;
}
if (nStones > 10){
picked = (int)(Math.random() * (4 - 1) + 1);
nStones = nStones - picked;
}
else
{
switch(nStones)
{
case 10:
picked = 3;
break;
case 9:
picked = 3;
break;
case 8:
picked = 2;
break;
case 7:
picked = 1;
break;
case 6:
picked = 2;
break;
case 5:
picked = 1;
break;
case 4:
picked = 1;
break;
case 3:
picked = 3;
break;
case 2:
picked = 2;
break;
case 1:
picked = 1;
break;
default:
endgame=true;
break;
}
nStones = nStones - picked;
}
return nStones;
}
public int humanMove(int nStones)
{
if (nStones <= 0)
{
winner = 2;
endgame = true;
}
Scanner in = new Scanner(System.in);
System.out.println("How many stones do you take? (Only 1 to 3)");
int n = in.nextInt();
nStones = nStones - n;
if (n == 1 || n == 2 || n == 3)
{
System.out.println("You picked: " + n);
nStones = nStones - n;
}
else
{
System.out.println("Invalid input");
System.out.println("No stones taken");
n=0;
}
return nStones;
}
}
/*
2 players take turns taking stones from a pile. On each move a player must take one, two or three stones. The player who takes the last stone wins.
b) Write a method computerMove:
/*
* Returns the correct number of stones to take
* (according to the winning strategy)
* when nStones remain in the pile.
* If such a move is not possible, returns a random number of stones to take
* Precondition: nStones > 0
*/
//c) Finish the method humanMove.
/*
* Prompts the user to take a number of stones.
* If the move is valid returns the number of stones taken;
* otherwise displays the correct error message –-
* "You are allowed to take 1, 2, or 3 stones, only."
* Or "Can't take that many; only <nStones> stones are left in the pile."
* -- and returns -1;
* Precondition: nStones > 0
d) Write a main method to:
/*
* Generate a random number of stones between 10 and 50
* Store the number of stones in nStones and keep track of it.
* Alternate calling the players, "Computer" and "Human"
* Determine when there is a winner, announce it and end the program.
* You may use more methods to do these steps. */
You cannot use a non-static member in a static method, it makes no sense: non-static members (like your variable winner or your method humanMove) belong to an instance of a class (in this case an instance of GameforCompSci).
As for static members, they do not belong to a particular instance of GameforCompSci.
This way, you can't reference e.g. winner (non-static variable) in your main method (which is static) because it doesn't exist in this context actually: you're not in an instance of GameforCompSci.
Think of statics as "one thing". When something is static, there's only ever one of it.
Every time you reference it, your pointing to the same object.
When something isnt static, that means theres a separate copy of it for each instance of the object.
So static methods can only ever access other static variables, or things passed to it as parameters. It cant access non-static ones, as it wouldn't know which instance of it you were talking about.
Understanding static/non-static is pretty critical if you want to learn Java. It will save you a lot of work when you understand when to use each.
A static method can only reference other static methods and static fields. The main method must be a static method, but your humanMove and computerMove methods are not static, and while your endgame field is static, winner and nStones are not static.
There are two ways you can fix this. You could add a static keyword to those other fields and methods, or you could create a new, non-static method called, for example, play, and put the current contents of your main method in it. Then change endgame to not be static, and use the following main method to start your program:
public static void main(String[] args) {
GameforCompSci game = new GameforCompSci();
game.play();
}
This would create an instance of your class, and then call the instance method play, from which you could reference the other instance methods and instance variables.

Categories

Resources