Problem with adjusting health in Pokemon class - java

I have two classes called Pokemon.java and Move.java which contain methods for creating and modifying Pokemon and their moves. I've created all of the required methods, but I'm having trouble with the attack method, which is supposed to subtract an opponent's health when it's attacked.
Here is the code for the Pokemon.java class:
import java.util.ArrayList;
public class Pokemon
{
// Copy over your code for the Pokemon class here
// Private constants
private static final int MAX_HEALTH = 100;
private static final int MAX_MOVES = 4;
private String name;
private int health;
private int opponentHealth;
public static int numMovesForPokemon = Move.getNumOfMoves();
private Move move;
private static ArrayList<Move> moveListForPokemon = new ArrayList<Move>();
private String pokemonImage;
// Write your Pokemon class here
public Pokemon(String theName, int theHealth)
{
name = theName;
if(theHealth <= MAX_HEALTH)
{
health = theHealth;
}
}
public Pokemon(String name, String image)
{
this.name = name;
health = 100;
pokemonImage = image;
}
public Pokemon(String theName)
{
name = theName;
}
public void setImage(String image)
{
pokemonImage = image;
}
public String getImage()
{
return pokemonImage;
}
public String getName()
{
return name;
}
public int getHealth()
{
return health;
}
public boolean hasFainted()
{
if(health <= 0)
{
return true;
}
else
{
return false;
}
}
public boolean canLearnMoreMoves()
{
if(numMovesForPokemon < 4)
{
return true;
}
else
{
return false;
}
}
public boolean learnMove(Move other)
{
if(canLearnMoreMoves())
{
moveListForPokemon = Move.getList();
moveListForPokemon.add(other);
numMovesForPokemon++;
return true;
}
else
{
return false;
}
}
public void forgetMove(Move other)
{
moveListForPokemon.remove(other);
}
public static ArrayList<Move> displayList()
{
return moveListForPokemon;
}
public boolean knowsMove(Move move)
{
if(moveListForPokemon.contains(move))
{
return true;
}
else
{
return false;
}
}
public boolean knowsMove(String moveName)
{
if(moveListForPokemon.contains(move.getName()))
{
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, Move move)
{
if(knowsMove(move))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
return true;
}
else
{
return false;
}
}
public boolean attack(Pokemon opponent, String moveName)
{
if(knowsMove(moveName))
{
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
return true;
}
else
{
return false;
}
}
public String toString()
{
return pokemonImage + "\n" + name + " (Health: " + health + " / " + MAX_HEALTH + ")";
}
// Add the methods specified in the exercise description
}
Here is the code for the Move.java class:
import java.util.ArrayList;
public class Move
{
// Copy over your code for the Move class here
private static final int MAX_DAMAGE = 25;
private String name;
private int damage;
public static int numMoves;
private static ArrayList<Move> moveList = new ArrayList<Move>();
public Move(String theName, int theDamage)
{
name = theName;
if(theDamage <= MAX_DAMAGE)
{
damage = theDamage;
}
}
public String getName()
{
return name;
}
public int getDamage()
{
return damage;
}
public static int getNumOfMoves()
{
return numMoves;
}
public static ArrayList<Move> getList()
{
return moveList;
}
public String toString()
{
return name + " (" + damage + " damage)";
}
// Add an equals method so we can compare Moves against each other
public boolean equals(Move other)
{
if(name.equals(other.getName()))
{
return true;
}
else
{
return false;
}
}
}
Finally, here is the code for PokemonTester.java where I test out the methods:
public class PokemonTester extends ConsoleProgram
{
private PokemonImages images = new PokemonImages();
public void run()
{
// Test out your Pokemon class here!
Pokemon p1 = new Pokemon("Charrizard", 100);
Pokemon p2 = new Pokemon("Pikachu", 100);
Move m1 = new Move("Flamethrower", 20);
Move m2 = new Move("Fire Breath", 15);
p1.learnMove(m1);
System.out.println(p1.knowsMove(m1));
System.out.println(p1.knowsMove("Flamethrower"));
System.out.println(p1.attack(p2, m1));
System.out.println(p2.getHealth());
}
}

I suppose your problem is this:
opponentHealth = opponent.getHealth();
opponentHealth -= move.getDamage();
This code has several problems:
I'd suggest using a local variable for opponentHealth instead of a class level field
The opponent doesn't gets to know that it's health was subtracted. You have to share this knowledge with him, e.g. by introducing a setter for health and then calling opponent.setHealth(opponentHealth)

You are first assigning the value of Oponent.getHealth() to the int variable oponentHealth which you then modify, however this modification does not affect the health of Opponent but instead just the oponentHealth variable, you either have to directly access and modify the health field of Opponent or implement some kind of setHealth(int health) method in the class Pokemon

Related

Creating a boolean to find a different kind of travel cup

Prompt: Many TravelCups do not have handles. To allow for this add a boolean instance variable to the TravelCup class. Change your constructors and methods to accommodate this change. Add any appropriate methods to the class this change requires. Demonstrate that changes work in your test runs.
I was able to do most of the project, but I get stuck here. I'm not sure if I'm supposed to create a new class or create a new object, but I've tried creating a new constructor and that just gives me an error. I've hit a dead-end and now I'm not sure what to do. Can anyone help?
Code:
public class Cup
{
// instance variables
private int volume; // in oz.
private String color;
private String material;
/**
* Default Constructor for objects of class Cup
*/
public Cup()
{
// initialise instance variables
volume = 8;
color = "white";
material = "ceramic";
}
public Cup(int v, String c, String m)
{
// initialise instance variables
volume = v;
color = c;
material = m;
}
public Cup(Cup other)
{
// initialise instance variables
volume = other.volume;
color = other.color;
material = other.material;
}
public void set(int v, String c, String m)
{
volume = v;
color = c;
material = m;
}
public String toString()
{
return "This is a " + color + " cup made of " + material
+ "\nIt holds " + volume + " oz. ";
}
/**
*
* #return the volume
*/
public int getVolume()
{
return volume;
}
public String getColor()
{
return color;
}
public String getMaterial()
{
return material;
}
public boolean equals(Cup other)
{
if(other == null)
return false;
else if( getClass() != other.getClass())
return false;
else
{
Cup otherCup = (Cup)other;
return volume == otherCup.volume && color.equals(otherCup.color) && material.equals(otherCup.material);
}
}
}
public class LogoCup extends Cup
{
private String logo;
private String slogan;
public LogoCup()
{
super( );
logo = "";
slogan = "";
}
public LogoCup(int v, String c, String m, String lg, String s)
{
super(v, c, m );
logo = lg;
slogan = s;
}
public LogoCup(LogoCup other)
{
super(other );
logo = other.logo;
slogan = other.slogan;
}
public String toString()
{
return super.toString()
+ " Logo: " + logo + " Slogan: " + slogan;
}
public boolean equals(LogoCup other)
{
if(other == null)
return false;
else if( getClass() != other.getClass())
return false;
else
{
LogoCup otherLogoCup = (LogoCup)other;
return logo.equals(otherLogoCup.logo) && slogan.equals(otherLogoCup.slogan) && super.equals( otherLogoCup);
}
}
public String getLogo()
{
return logo;
}
public String getSlogan()
{
return slogan;
}
}
public class TravelCup extends LogoCup
{
public TravelCup()
{
super();
}
public TravelCup(int v, String c, String m, String lg, String s)
{
super(v, c, m, lg, s );
}
public TravelCup(TravelCup other)
{
super(other );
}
public String toString()
{
return "Travel Cup! " + super.toString() + "\nEvery TravelCup has a lid!";
}
public boolean equals(Object other)
{
if(other == null)
return false;
else if( getClass() != other.getClass())
return false;
else
{
TravelCup otherTravelCup = (TravelCup)other;
return super.equals( otherTravelCup);
}
}
public boolean equals(Object handle);
{
}
}
The TravelCup may be implemented with the following updates:
added field boolean hasHandle, its getter and setting via constructors
updated constructors to use existing constructors using this(...)
updated toString and equals to include new field
(optional) added set method to set all parameters via call to super.set that needs to be added to LogoCup
class TravelCup extends LogoCup {
private boolean hasHandle = false;
public TravelCup() {
super();
}
public TravelCup(int v, String c, String m, String lg, String s) {
this(v, c, m, lg, s, false);
}
public TravelCup(int v, String c, String m, String lg, String s, boolean h) {
super(v, c, m, lg, s );
this.hasHandle = h;
}
public TravelCup(TravelCup other) {
super(other);
this.hasHandle = other.hasHandle;
}
public String toString() {
return "Travel Cup! " + super.toString() + ", hasHandle? " + hasHandle + "\nEvery TravelCup has a lid!";
}
public boolean equals(Object other)
{
if(other == null)
return false;
if (this == other)
return true;
if(getClass() != other.getClass())
return false;
TravelCup otherTravelCup = (TravelCup) other;
return super.equals(otherTravelCup) && this.hasHandle == otherTravelCup.hasHandle;
}
public boolean hasHandle() {
return hasHandle;
}
public void set(int v, String c, String m, String l, String s, boolean h)
{
super.set(v, c, m, l, s);
this.hasHandle = h;
}
}
// class LogoCup
class LogoCup extends Cup {
// ...
public void set(int v, String c, String m, String l, String s) {
super.set(v, c, m);
logo = l;
slogan = s;
}
}

Add Specific Object to a Binary Search Tree

I'm looking to add an object called "player" to a binary search tree based on how high the score of the player is, essentially like a scoreboard, but I'm not entirely certain how to add players to the binary tree; I'm curious how to go about writing the method, so I hope this question makes sense.
Here's a part of my BinaryTree class:
import java.util.Iterator;
public class BinaryTree implements Iterable<Player> {
private BinNode root;
public BinaryTree() {
root = null;
}
public boolean isEmpty() {
return root == null;
}
// TODO: add the given player to the binary tree based on the player's game score
public void add(final Player player) {
if (isEmpty())
root = new BinNode(player);
// this is SUUUPER placeholder
} ...
Here's the player class, :
public class Player implements Comparable<Player> {
private String name;
private int score;
private static final int MIN_SCORE = 0;
public Player(final String name, int score) {
this.name = name;
if (score < MIN_SCORE)
this.score = 0;
else
this.score = score;
}
public Player(final String name) {
this(name, MIN_SCORE);
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
#Override
public String toString() {
return name + ": " + score;
}
// TODO: compare player objects based on their scores
#Override
public int compareTo(Player other) {
return score - other.score;// I think this is a step in the right direction???
}
}
Here's my Binary Node class:
public class BinNode {
private Player player;
private BinNode left, right;
public BinNode() {
player = null;
left = right = null;
}
public BinNode(final Player player) {
this.player = player;
left = right = null;
}
public Player getPlayer() {
return player;
}
public BinNode getLeft() {
return left;
}
public BinNode getRight() {
return right;
}
public void setPlayer(final Player data) {
this.player = player;
}
public void setLeft(BinNode left) {
this.left = left;
}
public void setRight(BinNode right) {
this.right = right;
}
#Override
public String toString() {
return player.toString();
}
}
I recommend you not to use your own trees in production, but if you are just learn, then that's fine. To add a new entity to your tree, you have to find a place for it. In this code we search for it by comparing scores of players.
public void add(final Player player){
if (isEmpty()){
root = new BinNode(player);
}
else{
BinNode node = root;
while (true){
if (player.getScore() <= node.getPlayer().getScore()){
if (node.getLeft() == null){
node.getLeft() = new BinNode(player);
return;
}
else{
node = node.getLeft();
}
}
else{
if (node.getRight() == null){
node.getRight() = new BinNode(player);
return;
}
else {
node = node.getRight();
}
}
}
}
}

RPG game code error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting this error in my code. Can someone fix it and how is the code written? Can it be improved by maybe using setters and getters only?
Exception in thread "main" java.lang.NullPointerException
at Player.attack(Player.java:72)
at Main.main(Main.java:15)
My code:
Player.java
public class Player {
String name;
String race;
int hp;
int power;
int armour;
Weapon weapon;
public Player (String n, String r, int h, int p, int a) {
name = n;
race =r;
hp = h;
power = p;
armour = a;
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setRace (String r) {
race = r;
}
public String getRace() {
return race;
}
public void setHP (int h) {
hp = h;
}
public int getHP() {
return hp;
}
public void setPower (int p) {
power = p;
}
public int getPower() {
return power;
}
public void setArmour (int a) {
armour = a;
}
public int getArmour() {
return armour;
}
public boolean dead() {
return hp <= 0;
}
public boolean equip(Weapon weapon) {
this.weapon = weapon;
return true;
}
public boolean receiveDamage(int i) {
if ((hp - i) > 0) {
hp = hp - i;
return true;
}
hp = 0;
return false;
}
public boolean attack(Player player) {
return player.receiveDamage(weapon.useWeapon());
}
}
Main.java
public class Main {
public static void main(String args[]) {
Player Mensch = new Player("Mensch", "Mensch", 85, 12, 10);
Player Ork = new Player("Shrek", "Ork", 50, 14, 6);
Weapon MenschW = new Weapon("mächtiges Schwert", 15, 100);
Weapon OrkW = new Weapon("große Axt", 7, 100);
Mensch.equip(Mensch.weapon);
Ork.equip(Ork.weapon);
while (!Mensch.dead() && !Ork.dead() ) { //Alternativ: for (player hp >=0)
System.out.println("Mensch gegen Ork " + Mensch.attack(Ork));
if (Mensch.dead() || Ork.dead()) {
break;
}
System.out.println("Mensch gegen Ork " + Ork.attack(Mensch));
}
System.out.println("Ork ist tot: " + Ork.dead());
System.out.println("Mensch ist tot: " + Mensch.dead());
}
}
Weapon.java
import java.util.concurrent.ThreadLocalRandom;
public class Weapon {
String name;
int damage;
int hp;
public Weapon(String string, int d, int hp) {
// TODO Auto-generated constructor stub
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setDamage (int d) {
damage = d;
}
public int getDamage() {
return damage;
}
public void setWHP (int h) {
hp = h;
}
public int getWHP() {
return hp;
}
public int useWeapon() {
if
(broken())
return 0;
hp = hp - 5;
return (damage / 2) + random();
}
private int random() {
return ThreadLocalRandom.current().nextInt(1, damage + 1);
}
private boolean broken() {
return hp <= 0;
}
}
I know its a lot of code but I keep getting the same error, also I'm quite new to java so I would appreciate some tips or suggestions to make my code better or more failsave. The code doesn't do much yet but it will (hopefully) be a simple game soon in which two characters fight eachother with some calculations on damageoutput of each player. In this case a Human and Ork. Feel free to try it out
Change
Mensch.equip(Mensch.weapon); // Mensch.weapon is not initialized in constructor so it is null.
Ork.equip(Ork.weapon); // Ork.weapon is not initialized in constructor so it is null as well.
To
// Use your newly created weapons in the main instead.
Mensch.equip(MenschW );
Ork.equip(OrkW);

How to increment variable whenever a method is called

I am just in learning phase & here I am using some polymorphism technique. This is the code:
package com.company;
class Car{
private String name;
private int cylinder;
private boolean engine;
private int wheels;
public Car(String name, int cylinder) {
this.name = name;
this.cylinder = cylinder;
this.engine = true;
this.wheels = 4;
}
public String startEngine(int fuel){
if(fuel>0){
return "Start button pressed";
} else{
return "First fill some fuel";
}
}
public String accelerate(int speed){
return "Car is accelerated with speed " + speed;
}
public String brake(int speed){
return "Brake is presses. Now speed is " + speed;
}
public String getName() {
return name;
}
public int getCylinder() {
return cylinder;
}
}
class Fortuner extends Car{
public Fortuner() {
super("Fortuner", 4);
}
#Override
public String accelerate(int speed) {
return "Fortuner is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Fortuner is moving with " + speed + " kph";
}
}
class Hondacity extends Car{
public Hondacity() {
super("Hinda City", 6);
}
#Override
public String accelerate(int speed) {
return "Honda City is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Honda City is moving with " + speed + " kph";
}
}
class Omni extends Car{
public Omni() {
super("Omni", 1);
}
#Override
public String accelerate(int speed) {
return "Omni is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Omni is moving with " + speed + " kph";
}
}
public class Main {
public static void main(String[] args) {
for(int j=0; j<3; j++){
Car car = speedup();
System.out.println(car.accelerate(50));
}
}
public static Car speedup() {
for(int i=0; i<3; i++){
switch(i){
case 0: return new Fortuner();
case 1: return new Hondacity();
case 2: return new Omni();
}
}
return null;
}
}
When I run it, it's giving output like this:
Fortuner is accelerated with speed 50 Fortuner is accelerated with
speed 50 Fortuner is accelerated with speed 50
But I want to give output something like this
Fortuner is accelerated with speed 50 Hondacity is accelerated with
speed 50 Omni is accelerated with speed 50
I know this is happening due to initialization each time when method runs. How can I solve it? Please apologize me for poor algorithm as I am just a learner.
Your method speedup() always returns a Fortuner, as it never gets any further. The return command always exits the loop. So if you want to get all the classes, you would have to do it like this:
public static void main(String[] args) {
for(int ID=0; ID<3; ID++){
Car car = speedup(ID);
System.out.println(car.accelerate(50));
}
}
public static Car speedup(int ID) {
switch(i){
case 0: return new Fortuner();
case 1: return new Hondacity();
case 2: return new Omni();
}
return null;
}
In your method speedup() the value of j each time is 0. so it always return Fortuner. I have removed this method to solve it.
class Car {
private String name;
private int cylinder;
private boolean engine;
private int wheels;
public Car(String name, int cylinder) {
this.name = name;
this.cylinder = cylinder;
this.engine = true;
this.wheels = 4;
}
public Car() {
}
public String startEngine(int fuel){
if(fuel>0){
return "Start button pressed";
} else{
return "First fill some fuel";
}
}
public String accelerate(int speed){
return "Car is accelerated with speed " + speed;
}
public String brake(int speed){
return "Brake is presses. Now speed is " + speed;
}
public String getName() {
return name;
}
public int getCylinder() {
return cylinder;
}
}
class Fortuner extends Car{
public Fortuner() {
super("Fortuner", 4);
}
#Override
public String accelerate(int speed) {
return "Fortuner is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Fortuner is moving with " + speed + " kph";
}
}
class Hondacity extends Car{
public Hondacity() {
super("Hinda City", 6);
}
#Override
public String accelerate(int speed) {
return "Honda City is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Honda City is moving with " + speed + " kph";
}
}
class Omni extends Car{
public Omni() {
super("Omni", 1);
}
#Override
public String accelerate(int speed) {
return "Omni is accelerated with speed " +speed;
}
#Override
public String brake(int speed) {
return "Now your Omni is moving with " + speed + " kph";
}
}
public class Main {
public static void main(String[] args) {
for(int j=0; j<3; j++){
Car car = null;
switch (j) {
case 0: car = new Fortuner();
break;
case 1: car = new Hondacity();
break;
case 2: car = new Omni();
break;
}
System.out.println(car.accelerate(50));
}
}
}

Object in a 2d array keeps on resetting and I don't know why

I'm trying to make a tic tac toe game, and it works fine when the first X or O is inputted, but when the second is inputted the previous X or O is deleted and the new one is put in. I have no idea why this is happening.
import java.util.Scanner;
public class Play {
public static void main(String[] args){
Scanner kbd=new Scanner(System.in);
TicTacToeBoard t=new TicTacToeBoard(3, 3);
t.startBoard();
XO xo1=new XO();
xo1.setTurns(1);
XO xo2=new XO();
xo2.setTurns(0);
System.out.println("Player 1, what is your name?");
String n1=kbd.nextLine();
System.out.println("Player 2, what is your name?");
String n2=kbd.nextLine();
System.out.println(t);
while(!t.winner()&&!t.full()){
if(t.getTurnCnt()%2==0){
System.out.println(n1+"(X): ");
int x1=kbd.nextInt();
int y1=kbd.nextInt();
t.add(x1, y1, xo1);
System.out.println(t);
}
//this is where the board resets
else{
System.out.println(n2+"(O): ");
int x2=kbd.nextInt();
int y2=kbd.nextInt();
t.add(x2, y2, xo2);
System.out.println(t);
}
TicTacToeBoard Class:
public class TicTacToeBoard extends Board{
private XO[][] board;
private int turnCnt;
public TicTacToeBoard(int r, int c){
super(r, c);
board=new XO[r][c];
turnCnt=0;
}
public void startBoard(){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
board[i][j]=new XO();
board[i][j].setName("-");
}
}
}
public void setTurnCnt(int t){
turnCnt=t;
}
public XO[][] setBoard(XO[][] b){
return b;
}
public XO[][] getBoard(){
return board;
}
public int getTurnCnt(){
return turnCnt;
}
public boolean add(int x, int y, XO x1){
if(x<=this.getRows()&&y<=this.getCols()&&(board[x-1][y-1].getName().equals("-"))){
board[x-1][y-1].setName(x1.getName());
turnCnt++;
return true;
}
else
System.out.println("error");
return false;
}
public boolean winner(){
boolean t=false;
for(int i=0;i<3;i++){
if(board[i][0].equals(board[i][1], board[i][2])||board[0][i].equals(board[1][i], board[2][i])||board[0][0].equals(board[1][1], board[2][2])||board[2][0].equals(board[1][1], board[0][2]))
t=true;
}
return t;
}
public boolean XWinner(){
boolean t=false;
for(int i=0;i<3;i++){
if((board[i][0].equals(board[i][1], board[i][2])&&board[i][1].getName().equals("X"))||(board[0][i].equals(board[1][i], board[2][i])&&board[0][i].getName().equals("X"))||(board[0][0].equals(board[1][1], board[2][2])&&board[0][0].getName().equals("X"))||(board[2][0].equals(board[1][1], board[0][2])&&board[2][0].getName().equals("X")))
t=true;
}
return t;
}
public boolean full(){
boolean t=true;
for(int r=0;r<3;r++){
for(int c=0;c<3;c++){
if(board[r][c].getName()=="-")
t=false;
}
}
return t;
}
public String toString(){
return "\t\t\tCol\n\t\t1\t2\t3\nRow\t1\t"+board[0][0]+"\t"+board[0][1]+"\t"+board[0][2]+"\n\t2\t"+board[1][0]+"\t"+board[1][1]+"\t"+board[1][2]+"\n\t3\t"+board[2][0]+"\t"+board[2][1]+"\t"+board[2][2];
}
}
XO class:
public class XO {
private String name;
private int turn;
public XO(){
turn=-1;
}
public int getTurns(){
return turn;
}
public String getName(){
if(this.getTurns()==1)
name="X";
else if(this.getTurns()==0)
name="O";
else
name="-";
return name;
}
public void setName(String n){
name=n;
}
public void setTurns(int t){
turn=t;
}
public boolean equals(XO x1, XO x2){
if (x1.getName().equals(this.getName())&&x2.getName().equals(this.getName())&&this.getName()!="-")
return true;
else
return false;
}
public String toString(){
return name;
}
}
The problem is on your function
public String getName(){
if(this.getTurns()==1)
name="X";
else if(this.getTurns()==0)
name="O";
else
name="-";
return name;
}
Every time is called the name field is updated despite it is a getter method! This is not a best practice.
Let's go step by step:
the user gives his coordinates.
the name is set to the correct value: "X" or "O"
the board is printed (calling XO.toString (using name field direct
no through any getter
The status of the board is evaluated using the getName getter and
now is when the name got back to "-" because the turn has not been
changed.
Finally, I think that you can simplify XO class. Turn field does not add any worth. It seems enough to use the name field itself. And the if statement is redundant because the boolean expression inside the if is just what you want to return.
class XO {
String name="-";
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public boolean equals(XO x1, XO x2){
return(x1.getName().equals(this.getName())&&x2.getName().equals(this.getName())&&this.getName()!="-");
}
#Override
public String toString() {
return getName();
}
}
As an example, this can be the final code. Notice that more refactor can be done i.e. use an enum for XO status.
import java.util.Scanner;
public class Play {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
TicTacToeBoard t = new TicTacToeBoard(3, 3);
t.startBoard();
XO xo1 = new XO();
xo1.setName("O");
XO xo2 = new XO();
xo2.setName("X");
System.out.println("Player 1, what is your name?");
String n1 = kbd.nextLine();
System.out.println("Player 2, what is your name?");
String n2 = kbd.nextLine();
System.out.println(t);
while (!t.winner() && !t.full()) {
if (t.getTurnCnt() % 2 == 0) {
System.out.println(n1 + "(X): ");
int x1 = kbd.nextInt();
int y1 = kbd.nextInt();
t.add(x1, y1, xo1);
System.out.println(t);
}
//this is where the board resets
else {
System.out.println(n2 + "(O): ");
int x2 = kbd.nextInt();
int y2 = kbd.nextInt();
t.add(x2, y2, xo2);
System.out.println(t);
}
}
}
}
class TicTacToeBoard {
private XO[][] board;
private int turnCnt;
public TicTacToeBoard(int r, int c){
board=new XO[r][c];
turnCnt=0;
}
public void startBoard(){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
board[i][j]=new XO();
board[i][j].setName("-");
}
}
}
public void setTurnCnt(int t){
turnCnt=t;
}
public XO[][] setBoard(XO[][] b){
return b;
}
public XO[][] getBoard(){
return board;
}
public int getTurnCnt(){
return turnCnt;
}
public boolean add(int x, int y, XO x1){
if(x<=this.getRows()&&y<=this.getCols()&&(board[x-1][y-1].getName().equals("-"))){
board[x-1][y-1].setName(x1.getName());
turnCnt++;
return true;
}
else
System.out.println("error");
return false;
}
public boolean winner(){
boolean t=false;
for(int i=0;i<3;i++){
if(board[i][0].equals(board[i][1], board[i][2])||board[0][i].equals(board[1][i], board[2][i])||board[0][0].equals(board[1][1], board[2][2])||board[2][0].equals(board[1][1], board[0][2]))
t=true;
}
return t;
}
public boolean XWinner(){
boolean t=false;
for(int i=0;i<3;i++){
if((board[i][0].equals(board[i][1], board[i][2])&&board[i][1].getName().equals("X"))||(board[0][i].equals(board[1][i], board[2][i])&&board[0][i].getName().equals("X"))||(board[0][0].equals(board[1][1], board[2][2])&&board[0][0].getName().equals("X"))||(board[2][0].equals(board[1][1], board[0][2])&&board[2][0].getName().equals("X")))
t=true;
}
return t;
}
public boolean full(){
boolean t=true;
for(int r=0;r<3;r++){
for(int c=0;c<3;c++){
if(board[r][c].getName()=="-")
t=false;
}
}
return t;
}
public String toString(){
return "\t\t\tCol\n\t\t1\t2\t3\nRow\t1\t"+board[0][0]+"\t"+board[0][1]+"\t"+board[0][2]+"\n\t2\t"+board[1][0]+"\t"+board[1][1]+"\t"+board[1][2]+"\n\t3\t"+board[2][0]+"\t"+board[2][1]+"\t"+board[2][2];
}
public int getRows() {
return 3;
}
public int getCols() {
return 3;
}
}
class XO {
String name="-";
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public boolean equals(XO x1, XO x2){
return(x1.getName().equals(this.getName())&&x2.getName().equals(this.getName())&&this.getName()!="-");
}
#Override
public String toString() {
return getName();
}
}

Categories