I am about to complete a text based java board game (Very basic). And I am stuck on this last thing -
Basically what happens is when a user has types 'roll' to roll the virtual die. Then depending on the results an array gets updated to change the location of 'o' (which makes it look like there counter has been moved). I have figured out how to make this for the first roll.
But what I cannot figure out is how to make the second roll and first roll add up (and so on with third and fourth roll).
(example -
Roll 1: Player rolls the die - gets a 3 - moves to 3rd position on the board (solved)
Roll 2: The game remembers that the last roll was a 3 - player rolls a 4 - updates the board and moves the counter to number 7)
Here is a snippet of the relevant code:
public void play(String p1Name2, String p2Name2){
Scanner user_input = new Scanner(System.in);
Random rn = new Random();
String p1Roll = null,p2Roll;
int[] p1r = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
int b= 0,c= 0,d = 0,e = 0,g = 0;
while(array1[10] != 'o'){
c++;
if(b==0) {
int i =1;
System.out.println("Player 1, type roll to roll the die. ");
p1Roll = user_input.next();
if(p1Roll.equalsIgnoreCase("roll")){
p1r[c] = rn.nextInt(6);
p1r[c] += 1;
System.out.println("You rolled a: " + p1r[c]);
for(int f = 0; f< 10; f++ ){
if(array1[f] == 'o'){
array1[f] = 'x';
array1[p1r[c]] = 'o';
if(i ==1){
this.board();
i = 0;
}
}
}
}
if(b==1) {
}
}
}
}
and
public void board(){
System.out.println(" 1 2 3 4 (5) 6 7 8 9 10 11");
System.out.println("Player 1: " + array1[0]+ " " + array1[1] + " " + array1[2]+ " " + array1[3] + " " + array1[4]+ " " + array1[5] + " " + array1[6]+ " " + array1[7] + " " + array1[8]+ " " + array1[9] + " " + array1[10]);
System.out.println("Player 2: " + array2[0]+ " " + array2[1] + " " + array2[2]+ " " + array2[3] + " " + array2[4]+ " " + array2[5] + " " + array2[6]+ " " + array2[7] + " " + array2[8]+ " " + array2[9] + " " + array2[10]);
}
Finally, here is the console output:
Player 1, type roll to roll the die.
roll
You rolled a: 4
1 2 3 4 (5) 6 7 8 9 10 11
Player 1: x x x x o x x x x x x
Player 2: o x x x x x x x x x x
Player 1, type roll to roll the die.
roll
You rolled a: 4
1 2 3 4 (5) 6 7 8 9 10 11
Player 1: x x x x o x x x x x x
Player 2: o x x x x x x x x x x
Player 1, type roll to roll the die.
roll
You rolled a: 2
1 2 3 4 (5) 6 7 8 9 10 11
Player 1: x x o x x x x x x x x
Player 2: o x x x x x x x x x x
Player 1, type roll to roll the die.
You could change the code as follows:
public void play(String p1Name2, String p2Name2){
Scanner user_input = new Scanner(System.in);
Random rn = new Random();
String p1Roll = null,p2Roll;
int[] p1r = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
int b= 0,c= 0,d = 0,e = 0,g = 0;
while(array1[10] != 'o'){
c++;
if(b==0) {
int i =1;
System.out.println("Player 1, type roll to roll the die. ");
p1Roll = user_input.next();
if(p1Roll.equalsIgnoreCase("roll")){
p1r[c] = rn.nextInt(6);
p1r[c] += 1;
System.out.println("You rolled a: " + p1r[c]);
for(int f = 0; f< 10; f++ ){
if(array1[f] == 'o'){
array1[f] = 'x';
/** Update Current Position **/
array1[p1r[f] + p1r[c]] = 'o';
if(i == 1){
this.board();
i = 0;
}
break;
}
}
}
}
}
}
However, note that you're currently risking to get ArrayIndexOutOfBoundException in array[p1r[c]], as well as in the updated version. Hence, I would suggest you to address that, e.g.using moduled accesses array[(p1r[c%p1r.length]%array.length)]. It depends on the game behaviour you would like to have in such situations.
Hope it helps!
You asked me how it would look like in objects. it would look like this:
The group holds all the players.
The players have a board.
The board tracks each players location.
import java.util.*;
import java.lang.*;
import java.io.*;
class Game
{
public static void main (String[] args) throws java.lang.Exception
{
Group group = new Group();
group.createPlayer("Michael");
group.createPlayer("Jeff");
group.createPlayer("Fred");
group.renderBoard();
int round = 1;
while(true) {
System.out.println("Game round "+round);
round++;
group.getInputs();
group.renderBoard();
if(group.isGameFinished()) {
Player winner = group.getWinner();
System.out.println("Player "+winner.getName() + " is the winner! Congratulations");
break;
}
}
}
}
class Group {
private ArrayList<Player> group;
public Group() {
this.group = new ArrayList<Player>();
}
public void createPlayer(String name) {
this.group.add(new Player(name));
}
public void renderBoard() {
Iterator<Player> it = this.group.iterator();
while(it.hasNext()) {
Player current = it.next();
current.renderBoard();
}
}
public void getInputs() {
Iterator<Player> it = this.group.iterator();
while(it.hasNext()) {
Player currentMove = it.next();
currentMove.getDiceRoll();
}
}
public boolean isGameFinished() {
Iterator<Player> it = this.group.iterator();
while(it.hasNext()) {
Player currentMove = it.next();
if(currentMove.isFinished()) {
return true;
}
}
return false;
}
public Player getWinner() {
Iterator<Player> it = this.group.iterator();
while(it.hasNext()) {
Player currentMove = it.next();
if(currentMove.isFinished()) {
return currentMove;
}
}
return new Player("Nobody");
}
}
class Player {
private Scanner user_input;
private Random rn;
private String name;
private Board board;
public Player(String name) {
this.name = name;
this.user_input = new Scanner(System.in);
this.rn = new Random();
this.board = new Board(11);
}
public void getDiceRoll() {
System.out.println("Player "+this.name+", type roll to roll the die. ");
String input = user_input.next();
if(input.equalsIgnoreCase("roll")) {
int dieRoll = rn.nextInt(6);
System.out.println("You rolled a "+dieRoll+"!");
this.board.updateLocation(dieRoll);
}
}
public String getName() {
return this.name;
}
public boolean isFinished() {
return this.board.isFinished();
}
public void renderBoard() {
System.out.println(this.name +" > "+this.board.renderBoard());
}
}
class Board {
private int size;
private int location;
public Board(int size) {
this.size = size;
this.location = size;
}
public void reset() {
this.location = this.size;
}
public boolean isFinished() {
return this.location <= 0;
}
public void updateLocation(int amount) {
this.location -= amount;
if(this.location < 0) {
this.location = 0;
}
}
public String renderBoard() {
StringBuilder builder = new StringBuilder();
for(int c=0;c<=this.size;c++) {
if(c == this.location) {
builder.append('o');
}
else {
builder.append('x');
}
builder.append(' ');
}
return builder.toString();
}
}
Related
I am stuck at a part where I am supposed to declare a string variable called "phrase", where it shouldn't loop, all the way through.
to give you an idea my task is: Similar to Option 1 except the user enters 'N' (instead of 'Q') when they are done entering results for the first team. Then, the program inputs a second team name and its results until 'Q' is entered. Outputs two statements, like the statements in option 1 followed by a third statement that says which team is in first place (based on the number of points)
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal // how would I make this appear in the same while loop?
L
L
O
L
L
W
L
L
Q
Sample output:
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
UPDATE:
My code:
else if (option == 2){
int counter = 0;
int totalpoints = 0;
String phrase = keyboard.next();
while(go){
String letter = keyboard.next();
if (letter.equals("W")){
pointsW++;
}
else if (letter.equals("L")){
pointsL++;
}
else if (letter.equals("O")){
pointsO++;
}
counter++;
if (letter.equals("N")){
totalpoints = pointsW + pointsL + pointsO;
counter--;
go = false;
}
}
int counter2 = 0;
int totalpoints2 = 0;
pointsW = 2;
pointsL = 0;
pointsO = 1;
String phrase2 = keyboard.next();
while (go2){
String letter2 = keyboard.next();
if (letter2.equals("W")){
pointsW++;
}
else if (letter2.equals("L")){
pointsL++;
}
else if (letter2.equals("O")){
pointsO++;
}
counter2++;
if (letter2.equals("Q")){
counter2--;
totalpoints2 = pointsW + pointsL + pointsO;
go2 = false;
}
}
System.out.println(phrase + " has played "+counter+" games and has earned "+totalpoints+" points");
System.out.println(phrase2 + " has played "+counter2+" games and has earned "+totalpoints2+" points");
if (totalpoints > totalpoints2){
System.out.println(phrase + " is in first place by "+(totalpoints - totalpoints2) + " points");
}else{
System.out.println(phrase2 + " is in first place by "+(totalpoints2 - totalpoints) + " points");
}
}
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
The issue: This is the output I am getting "Montreal played 8 games and has earned 11 points" where instead it should be "Montreal has played 8 games and has earned 3 points"
The output I am getting
You can reuse the same variables for individual points i.e. pointsW and pointsO because you do not want to retain their values till the end where you are publishing the results. The same is the case with the variable for the loop condition i.e. go and the variable used for inputting win/loss i.e. letter.
You will need arrays or different variables for storing total points, countings, and team name.
import java.util.Scanner;
public class Standings {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
int pointsW = 0;
int pointsO = 0;
String letter;
boolean go = true;
if (option == 2) {
// Variables for total points, counting, and name for the first team
int playedGamesTeamOne = 0;
int teamOnePoints = 0;
String teamOneName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamOne++;
if (letter.equals("N")) {
teamOnePoints = pointsW + pointsO;
playedGamesTeamOne--;
go = false;
}
}
// Reset common variables
go = true;
pointsW = 0;
pointsO = 0;
// Variables for total points, counting, and name for the second team
int playedGamesTeamTwo = 0;
int teamTwoPoints = 0;
String teamTwoName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamTwo++;
if (letter.equals("Q")) {
teamTwoPoints = pointsW + pointsO;
playedGamesTeamTwo--;
go = false;
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned "
+ teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned "
+ teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out
.println(teamOneName + " is in first place by " + (teamOnePoints - teamTwoPoints) + " points");
} else {
System.out
.println(teamTwoName + " is in first place by " + (teamTwoPoints - teamOnePoints) + " points");
}
}
}
}
A sample run:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
you can use this code for option two
Scanner keyboard = new Scanner(System.in);
int teamCounter = 1;
//String[] teamsNames = new String[2];
String teamOneName="";
String teamTwoName="";
//int[] playedGames = new int[2];
int playedGamesTeamOne = 0;
int playedGamesTeamTwo = 0;
//int[] points = new int[2];
int teamOnePoints = 0;
int teamTwoPoints = 0;
boolean firstTimeTeam1 = true;
boolean firstTimeTeam2 = true;
while (teamCounter <= 2) {
if (teamCounter == 1) {
if (firstTimeTeam1) {
teamOneName = keyboard.nextLine();
firstTimeTeam1 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamOnePoints += 2;
playedGamesTeamOne++;
} else if (letter.equals("L")) {
playedGamesTeamOne++;
} else if (letter.equals("O")) {
teamOnePoints += 1;
playedGamesTeamOne++;
} else if (letter.equals("N")) {
teamCounter++;
}
} else {
if (firstTimeTeam2) {
teamTwoName = keyboard.next();
firstTimeTeam2 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamTwoPoints += 2;
playedGamesTeamTwo++;
} else if (letter.equals("L")) {
playedGamesTeamTwo++;
} else if (letter.equals("O")) {
teamTwoPoints += 1;
playedGamesTeamTwo++;
} else if (letter.equals("Q")) {
teamCounter++;
}
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned " + teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned " + teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out.println(teamOneName + " is in first place by " + (teamOnePoints-teamTwoPoints) + " points");
} else {
System.out.println(teamTwoName + " is in first place by " + (teamTwoPoints-teamOnePoints) + " points");
}
So for yet ANOTHER project I am doing an RPG code. Like Dungeons and dragons. My particular problem is the attributes. Basically the application gives statistics to the player and then, in case the player does not like the stats they have recieved, the application gives them the option to reroll. The first roll does fine, however, if the user chooses to reroll, the stats (both the first and the next) add on to each other. Here is my code:
The Main Method:
package bagOfHolding;
public class Advanced {
public static void main(String [] args){
GameMaster.game();
}
}
The Dice Class (this rolls the stats for the statistics):
package bagOfHolding;
import java.util.Random;
public class DiceBag {
private static int sum;
public static int rollD6() {
int[] Dice = new int[3];
Random num = new Random();
for (int i = 0; i < Dice.length; i++) {
Dice[i] = num.nextInt((6)) + 1;
}
for (int i : Dice) {
sum += i;
}
return sum;
}
// public static int getSum() {
// return sum;
// }
// public static void setSum(int sum) {
// DiceBag.sum = sum;
// }
}
The Game Master (This does the whole game):
package bagOfHolding;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GameMaster {
public static void game() {
Hero.attributes();
}
public static void ReRoll() {
BufferedReader delta = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Would you like to reroll your hero? 1) Yes or 2) No");
System.out.println("Please enter a number");
System.out.println("Any number other than 1 or 2 will exit the application");
try {
String userInput = delta.readLine();
int input = Integer.parseInt(userInput);
if (input == 1) {
Hero.setStrength(DiceBag.rollD6());
Hero.setDexterity(DiceBag.rollD6());
Hero.setIntelligence(DiceBag.rollD6());
Hero.attributes();
} else if (input == 2) {
System.exit(0);
} else {
System.exit(0);
}
} catch (NumberFormatException NFE) {
System.out.println("Invalid");
} catch (IOException IOE) {
System.out.println("Invalid");
}
}
}
And the Hero class (this has all the statistics):
package bagOfHolding;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Hero {
/*
* Attributes - Randomly determined by 3d6
*
*/
/*
* -3 attributes - Strength - Damage bonus - If over 15 every pt = +1 (_++;)
* - Negative Damage Bonus - If under 10 every pt = -1 (_--;) - Dexterity
* -Strike bonus - every 2 pts over 14 = (_%2 + 1) - Negative Strike bonus -
* every 2 pts below 10 = (_%2 -1) - Dodge bonus - every 2 pts over 15 =
* (_%2 + 1) - Negative dodge bonus - every 2 pts below 11 = (_%2 -1) -
* Intelligence -Spell Strength Bonus - every pt over 15 = (++2) - Negative
* Spell Strength Bonus - every pt below 11 = (--2)
*
* Base Attributes - Health -Strength * 10 - MP - Intelligence *5
*/
private static int strength = DiceBag.rollD6();
private static int intelligence = DiceBag.rollD6();
private static int dexterity = DiceBag.rollD6();
public static int getIntelligence() {
return intelligence;
}
public static void setIntelligence(int intelligence) {
Hero.intelligence = intelligence;
}
public static int getDexterity() {
return dexterity;
}
public static void setDexterity(int dexterity) {
Hero.dexterity = dexterity;
}
public static int getStrength() {
return strength;
}
public static void setStrength(int strength) {
Hero.strength = strength;
}
public static void attributes() {
strength = getStrength();
System.out.println("Here is your hero: ");
// DiceBag.rollD6();
System.out.println("Strength = " + strength);
if (strength > 15) {
System.out.println("Damage Bonus = " + "+" + (strength - 15));
} else if (strength < 10) {
System.out.println("Negative Damage Bonus = " + "-" + (10 - strength));
} else {
System.out.println("You do not have damage bonus");
}
intelligence = getIntelligence();
System.out.println("Intelligence = " + intelligence);
if (intelligence > 15) {
System.out.println("Spell Strength Bonus = " + "+" + ((intelligence - 15) * 2));
} else if (strength < 11) {
System.out.println("Negative Spell Strength Bonus = " + "-" + ((11 - intelligence) * 2));
} else {
System.out.println("You do not have a spell strength bonus");
}
dexterity = getDexterity();
System.out.println("Dexterity = " + dexterity);
if (dexterity > 15 && dexterity % 2 == 0) {
System.out.println("Dodge Bonus = " + "+" + (dexterity - 15));
} else if (dexterity < 11 && dexterity % 2 == 0) {
System.out.println("Negative Dodge Bonus = " + "-" + (11 - dexterity));
} else {
System.out.println("You do not have a dodge bonus");
}
if (dexterity > 14 && dexterity % 2 == 0) {
System.out.println("Strike Bonus = " + "+" + (dexterity - 14));
} else if (dexterity < 10 && dexterity % 2 == 0) {
System.out.println("Negative Strike bonus = " + "-" + (10 - dexterity));
} else {
System.out.println("You do not have a strike bonus");
}
int health = strength * 10;
System.out.println("Health = " + health);
int MP = intelligence * 5;
System.out.println("MP = " + MP);
GameMaster.ReRoll();
}
}
DiceBag sum should be local to rollD6 rather than static.
Ok, so I was assigned to make a Dice program that could be called to roll a dice and return the side it landed on. I got the Dice part of it done. However when I run my program, my if statement doesn't execute to increment Counter if both die equal 6. What is wrong with my program.
This is the main:
public class PairOfDice {
public static void main(String[] args) {
int Counter = 0;
Dice D1 = new Dice();
Dice D2 = new Dice();
for (int X = 0; X <= 1000; X++)
{
D1.Roll();
D2.Roll();
if (D1.equals(6) && D2.equals(6))
{
Counter++;
}
else
{
System.out.print ("Dice 1 = " + D1 + " | ");
System.out.println ("Dice 2 = " + D2);
}
}
System.out.print ("There were " + Counter + " Box Cars");
}
}
And this is my Dice function:
public class Dice {
private int Side;
public Dice()
{
Roll();
}
public void Roll()
{
Side = (int)(Math.random() * 6 + 1);
}
public String toString()
{
String A;
A = Integer.toString(Side);
return A;
}
}
You seem to have missed what .Equals() means:
D1.equals(6)
D1 doesn't equal 6. D1 is an instance of a Dice object, and 6 is an integer. You need to determine if the integer value within D1 equals 6.
First, create a getter for that value on the Dice class:
public int getSide()
{
return Side;
}
Then use that in the comparisons:
if (D1.getSide() == 6 && D2.getSide() == 6)
You need to check if the value of the die equals the value 6. Right now you are comparing the value of dice object to a number which doesn't make sense. Override equals or provide a getter for the value of the die.
I figured it out All I did was change if (D1.equals(6) && D2.equals(6)) to if (D1.equals(6) && D2.equals(6)) and removed the else part of the if statement, and put the print out before the if statement.
This is the main:
public class PairOfDice {
public static void main(String[] args) {
int Counter = 0;
Dice D1 = new Dice();
Dice D2 = new Dice();
for (int X = 0; X <= 1000; X++)
{
D1.Roll();
D2.Roll();
System.out.print ("Dice 1 = " + D1 + " | ");
System.out.println ("Dice 2 = " + D2);
if (D1.Side == 6 && D2.Side == 6)
{
Counter++;
}
}
System.out.print ("There were " + Counter + " Box Cars");
}
}
This is Dice:
public class Dice {
int Side;
public Dice()
{
Roll();
}
public void Roll()
{
Side = (int)(Math.random() * 6 + 1);
}
public String toString()
{
String A;
A = Integer.toString(Side);
return A;
}
}
Please try below logic
public class PairOfDice {
public static void main(String[] args) {
int counter = 0;
Dice d1 = new Dice();
Dice d2 = new Dice();
for (int X = 0; X <= 1000; X++)
{
d1.roll();
d2.roll();
if (d1.getSide()==6 && d2.getSide()==6)
{
counter++;
}
else
{
System.out.print ("Dice 1 = " + d1 + " | ");
System.out.println ("Dice 2 = " + d2);
}
}
System.out.print ("There were " + counter + " Box Cars");
}
}
public class Dice {
private int side;
public Dice()
{
roll();
}
public void roll()
{
side = (int)(Math.random() * 6 + 1);
}
public String toString()
{
String A;
A = Integer.toString(side);
return A;
}
public int getSide() {
return side;
}
}
The queue generates an error if more than 3 names are entered into it:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at hotelobjects.Queue.addqueue(Queue.java:17)
at hotelobjects.HotelObjects.addCustomers(HotelObjects.java:82)
at hotelobjects.HotelObjects.main(HotelObjects.java:44)
Java Result: 1
How do I ensure that any names entered after the original 3 will be placed at the front of the queue - in a circular way.
package hotelobjects;
import java.util.*;
import java.io.*;
public class HotelObjects {
static Queue myQueue = new Queue();
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
String command;
Scanner input = new Scanner(System.in);
Room[] myHotel = new Room[10];
for (int x = 0; x < myHotel.length; x++) {
myHotel[x] = new Room();
}
System.out.println("10 Rooms Created");
while (true) {
System.out.print("\nEnter command or 'X' to exit: ");
command = input.next();
command = command.toLowerCase();
if (command.charAt(0) == 'x') {
System.exit(0);
}
if (command.charAt(0) == 'a') {
addCustomers(myHotel);
}
if (command.charAt(0) == '3') {
displayNames(myHotel);
}
}
}
private static void addCustomers(Room myHotel[]) {
String roomName;
int roomNum;
System.out.println("Enter room number (0-10) or 11 to exit:");
Scanner input = new Scanner(System.in);
roomNum = input.nextInt();
if (roomNum<11) {
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
roomName = roomName.toLowerCase();
myHotel[roomNum].setName(roomName);
myQueue.addqueue(roomName);
}
else {
System.exit(0);
}
}
private static void displayNames(Room[] myHotel) {
System.out.println("The last 3 names entered are: ");
for (int x = 0; x < 3; x++) {
myQueue.takequeue();
}
}
}
Here is the 'queue' class:
package hotelobjects;
public class Queue {
String qitems[] = new String[3];
int front = 0, end = 0;
void addqueue(String roomName) {
qitems[end] = roomName;
end++;
}
void takequeue() {
if (end > front) {
System.out.println("Name Entered : " + qitems[front]);
front++;
} else {
System.out.println("No Name");
}
}
}
Increment your index module the maximum number of elements in the queue:
void addqueue(String roomName) {
qitems[end] = roomName;
end = (end + 1) % 3;
}
So you get:
end = (0 + 1) % 3 = 1
end = (1 + 1) % 3 = 2
end = (2 + 1) % 3 = 0
end = (0 + 1) % 3 = 1
...
You should also change the takequeue() method to consider the fact that the queue is now circular. Something like this:
void takequeue() {
System.out.println("Name Entered : " + qitems[front]);
front = (front + 1) % 3;
}
It is also a good idea to create a constant to store the queue capacity instead of repeating the 3 value all over the code:
private static final int CAPACITY = 3;
afer program outputs a winner, i ask if user wants to play again or exit but for some reason scanner doesn't read this input(continue or not). I even put prompt for continuation outside the while loop but still no luck:
"|XXX|
| O |
| O|
Player X is a winner!
Do you want to play again? Enter Y for yes or N for no!
BUILD SUCCESSFUL (total time: 26 seconds)
"
This is code:
public class TicTacToeRunner
{
public static void main(String[] args)
{
int row;
int column;
Scanner in = new Scanner(System.in);
TicTacToe game = new TicTacToe();
String player = "X";
boolean done = false;
int moveCounter = 0;
String answer;
int noMovement = -2;
int toQuit = -1;
int movesToCheckWins = 5;
int movesToCheckTies = 7;
while (!done)
{
do
{
row = column = noMovement;
System.out.print("\n" + game);
System.out.print("Please make a move " + (moveCounter + 1) + "(" + player + ")\nRow for " + player.toUpperCase() + " (or -1 to exit): ");
if (in.hasNextInt()) //check if input is an integer
{
row = in.nextInt();
}
if (row == toQuit) //if entered -1 quit the game
{
done = true;
System.out.println("Player " +player.toUpperCase() + " ended the game !");
System.exit(0); //game termination
}
else
{
System.out.print("Column for " + player.toUpperCase() + ": ");
if(in.hasNextInt()) //check if input is an integer
{
column = in.nextInt();
}
}
}while(!game.checkForValidMove(row, column)); //end of do-while loop if checkForValidMove is false
moveCounter++;
game.set(row, column, player);
if (moveCounter >= movesToCheckWins) //check wins after 5 moves
{
if (game.checkForWin(row, column, player)) //if a winner
{
done = true;
System.out.println("\n" + game);
System.out.println("Player " + player.toUpperCase() + " is a winner!");
}
}
if (moveCounter >= movesToCheckTies) //Check for ties after 7 moves
{
if (game.checkForEarlyTie()) //check for early tie
{
done = true;
System.out.println("\n" + game);
System.out.println("Tie Game after " + moveCounter + " moves!");
}
}
// Switching players
if (player.equals("X"))
{
player = "O";
}
else
{
player = "X";
}
}
System.out.println("Do you want to play again? Enter Y for yes or N for no!");
answer = in.nextLine();
answer = answer.toLowerCase(); //change input to lowercase for bullet proofing
if(answer.equals("y"))
{
done = false;
player = "X";
moveCounter = 0;
game.resetTheGame();
}
else
{
System.exit(0); //program termination
}
}
}
using a do while loop. your work is easy..
import java.util.Scanner;
public class TicTacToeRunner {
public static void main(String[] args) {
int row;
int column;
Scanner in = new Scanner(System.in);
TicTacToe game = new TicTacToe();
String player = "X";
boolean done = false;
String choice = "";
int moveCounter = 0;
String answer;
int noMovement = -2;
int toQuit = -1;
int movesToCheckWins = 5;
int movesToCheckTies = 7;
do{
while (!done) {
do {
row = column = noMovement;
System.out.print("\n" + game);
System.out.print("Please make a move " + (moveCounter + 1) + "(" + player + ")\nRow for " + player.toUpperCase() + " (or -1 to exit): ");
if (in.hasNextInt()) // check if input is an integer
{
row = in.nextInt();
}
if (row == toQuit) // if entered -1 quit the game
{
done = true;
System.out.println("Player " + player.toUpperCase() + " ended the game !");
System.exit(0); // game termination
} else {
System.out.print("Column for " + player.toUpperCase() + ": ");
if (in.hasNextInt()) // check if input is an integer
{
column = in.nextInt();
}
}
} while (!game.checkForValidMove(row, column)); // end of do-while
// loop if
// checkForValidMove
// is false
moveCounter++;
game.set(row, column, player);
if (moveCounter >= movesToCheckWins) // check wins after 5 moves
{
if (game.checkForWin(row, column, player)) // if a winner
{
done = true;
System.out.println("\n" + game);
System.out.println("Player " + player.toUpperCase() + " is a winner!");
}
}
if (moveCounter >= movesToCheckTies) // Check for ties after 7 moves
{
if (game.checkForEarlyTie()) // check for early tie
{
done = true;
System.out.println("\n" + game);
System.out.println("Tie Game after " + moveCounter + " moves!");
}
}
// Switching players
if (player.equals("X")) {
player = "O";
} else {
player = "X";
}
}
System.out.println("Do you want to play again? Enter Y for yes or N for no!");
choice = in.nextLine();
}while(choice.equals("y")||choice.equals("Y"));
}
}