single dimensional array battleship code - java

I am beginner in java. I was trying to emulate the single dimension array battle ship code from heads first java book. The code is not failing, but I am not able to make it work properly.
Example: [1,2,3] is the array which contains the location of the battle ship. If I guess any number except 1, it is displaying as miss. But if I guess it as 1 three times (length of battleship) in a row I am making it as kill. I am not able to figure out this issue.
Could you please help me out here. The code is posted below:
package battleship;
public class battleship {
public int[] battleship = new int[3];
public int numofhits = 0;
String result = "miss";//instance variables complete
//setter method to initialize the array which holds the battle ship location
public void setbattleshiploc(int startpos) {
int i = 0;
for(i = 0; i < battleship.length; i++) {
battleship[i] = startpos + i;
System.out.println(battleship[i]);
}
System.out.println("initialized array is: " + java.util.Arrays.toString(battleship));
}
//getter method to print the set battleship array
public int[] getbattleshiploc() {
System.out.println("Battleship array is: " + battleship);
return battleship;
}
//checking whether user guess inside the battleship array location
public String guessloc(int guessnum) {
//int i = 0;
for(int cell : battleship) {
System.out.println("Guessed number is: " + guessnum + " array element: " + battleship[cell]);
System.out.println("cell: "+ cell + " ,battleship[cell]: " + battleship[cell] );
if(cell == guessnum) {
numofhits++;
if(numofhits == 3) {
result = "kill";
return result;
}//if the hits are 3 then return kill indicating that no more battle ship is available
else {
result = "hit";
return result;
}//end inner else
}//end outer if
else {
//numofhits++;
result = "miss";
return result;
}//end the if-else
}//end for loop
return "finished";
}//end function guessloc
}//end class
package battleship;
import java.util.Scanner;
public class gamelauncher {
public Scanner[] reader;
public static void main(String[] args) {
String result = "miss";
int numofguess = 0;
//int loopnum = 0;
battleship launchgame = new battleship();//launch the game
int startpos = (int) (Math.random() * 5);//generate random number between 0-4
//int[] location = {startpos, startpos + 1, startpos + 2};//initialize three consecutive array element
launchgame.setbattleshiploc(startpos);//set the array as the battleship location using setter
//display the battleship position
System.out.println("Battle shipt positions are: " + startpos +" ," + startpos+1 + " ," + startpos+2);
System.out.println("the battle ship array is: " + launchgame.getbattleshiploc());
//int[] battleshiplocation = launchgame.getbattleshiploc();
System.out.println(java.util.Arrays.toString(launchgame.getbattleshiploc()));
while(result != "kill") {
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int guess = reader.nextInt(); //get the user input integer
//reader.close();//close the scanner
//loopnum++;
numofguess++;
if(guess < 0 || guess > 7) {
System.out.println("Maximum space available is 7 units(0-6) and battleship length is 3 units, Please provide the location accordingly");
continue;
}//close if loop and go to the loop execution if the guess is not within the limits
else {
result = launchgame.guessloc(guess);
System.out.println("response from guessing method: " + result);
//get the status(hit/miss/kill) back from guess location method
if(result == "kill") {
System.out.println("We have destroyed all the parts of battle ship and it took " + numofguess +" guesses" );
break;//get out of the loop as we have destroyed everything
}//end kill
else if(result == "hit") {
System.out.println("You have destroyed " + launchgame.numofhits+" parts of batlleship, please continue");
continue;
}
else {
System.out.println("It's a miss dumbo, try again");
continue;
}
}//end outer else statement
}//end while loop
}//end main method
}//end class

I can help you by giving you this function a bit changed. Please try to fix the rest of your code on your own. It will give you important experience.
public String guessloc(int guessnum) {
for(int i=0;i<battleship.length;++i) {
if(battleship[i] == guessnum) { //it's a hit
battleship[i] = -1; //you cant hit it again, so change it
if(++numofhits == 3) {
return "kill";
}else
return "hit";
}
}
return "miss"; //miss should be outside of the for loop
}

I believe the problem is that when you are comparing Strings u are using == instead of .equals() so your code should like like this:
if(result.equals("kill"))

Related

While loop not terminating when an array equals the terminate condition array. Java. First java class please be patient. Thank you

Was wondering if there was a reason that the while loop was not terminating if the arrays equal eachother, the one condition was an array set to all 2s and then when the Die array reaches all 2s I wanted the while loop to terminate. Thank you for any help.
Stuck in the mud dice game, 2 players will roll 5 dice each, and the person with the highest total wins, if one player rolls a 2
they are stuck in the mud and unable to continue rolling for the rest of the game
import java.util.*;
public class StuckInTheMud {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is player ones name?");
String firstPlayer = keyboard.nextLine();
System.out.println("What is player twos name?");
String secondPlayer = keyboard.nextLine();
Player playerOne = new Player(firstPlayer);
Player playerTwo = new Player(secondPlayer);
while (playerOne.getDice() != playerOne.endGame() || playerTwo.getDice() != playerTwo.endGame()) // this is the while loop that wont terminate
{
pressEnterKeyToContinue(firstPlayer); // these are the turns looping
playerOne.playerTurn(firstPlayer);
pressEnterKeyToContinue(secondPlayer);
playerTwo.playerTurn(secondPlayer);
}
}
public static void pressEnterKeyToContinue(String playerName) // using a continue method so the game doesn't contine on its own
{
System.out.println("\n" + playerName + ", press Enter key when you are ready to roll!");
Scanner nextTurn = new Scanner(System.in);
nextTurn.nextLine();
}
}
import java.util.*;
public class Player { // this is the player class
private int score;
private Die[] dice = new Die[6];
private String playerName;
private int roundScore;
private int totalScore;
public Player(String playerAlias) {
playerAlias = playerName;
score = 0;
for (int i = 0; i != dice.length; i++) {
dice[i] = new Die(6);
dice[i].setValue(1);
}
}
public void playerTurn(String playerName) {
roundScore = 0;
int twoRoll = 0;
System.out.print(playerName + " it is your turn, here come the dice.\n");
for (int i = 0; i != dice.length; i++) // This for loop will add random dice roll integers into the players array
{
if (dice[i].getValue() != 2) {
dice[i].roll();
if (dice[i].getValue() != 2) {
System.out.println("For roll number " + (i + 1) + " you got a " + dice[i].getValue() + "!");
roundScore(dice[i].getValue());
} else {
System.out.println("For roll number " + (i + 1) + ", you got a 2! Die " + (i + 1) + " is now stuck in the mud!");
twoRoll = 1;
}
} else {
System.out.println("Die " + (i + 1) + " is stuck in the mud since you rolled a 2, it cannot be used for the rest of the game!");
}
}
if (twoRoll == 0) {
System.out.println("\nYour total score this round was " + getRoundScore() + ".");
totalScore(roundScore);
System.out.println(playerName + ", your total score for the game is " + getTotalScore() + "!");
} else {
System.out.println("\nSince you rolled a 2, the score for this round is 0");
roundScore = 0;
totalScore(roundScore);
System.out.println(playerName + ", your total score for the game is " + getTotalScore() + "!");
}
}
public void roundScore(int singleRoll) {
roundScore += singleRoll;
}
public int getRoundScore() {
return roundScore;
}
public void totalScore(int roundScore) {
totalScore += roundScore;
}
public int getTotalScore() {
return totalScore;
}
public Die[] getDice() {
return dice;
}
public Die[] endGame() {
Die[] endGame = new Die[6];
for (int i = 0; i != endGame.length; i++) {
endGame[i] = new Die(6);
endGame[i].roll();
endGame[i].setValue(2);
}
return endGame;
}
}
// Die Class
// 4/21/22
// Zachary Strickler
import java.util.Random;
/**
The Die class simulates a six-sided die.
*/
public class Die // this is the die class
{
private int sides; // Number of sides
private int value; // The die's value
/**
The constructor performs an initial
roll of the die.
#param numSides The number of sides for this die.
*/
public Die(int numSides) {
sides = numSides;
roll();
}
/**
The roll method simlates the rolling of
the die.
*/
public void roll() {
// Create a Random object.
Random rand = new Random();
// Get a random value for the die.
value = rand.nextInt(sides) + 1;
}
/**
getSides method
#return The number of sides for this die.
*/
public int getSides() {
return sides;
}
/**
getValue method
#return The value of the die.
*/
public int getValue() {
return value;
}
public int setValue(int setValue) {
value = setValue;
return value;
}
}
You while loop test includes
playerTwo.getDice() != playerTwo.endGame()
By using the = operator, you are saying 'are these two arrays the same array object?'. Looking at the endGame method you can see that can never be true, you are creating a new array object every time you call that method, so could never be the same one as
playerTwo.getDice().
Instead of checking to see if they are the same object, you really want to know if they have the same values. There are some other ways of doing that. I'll give you a hint, look at java.util.Arrays package.
https://www.geeksforgeeks.org/java-util-arrays-equals-java-examples/
https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
https://www.geeksforgeeks.org/compare-two-arrays-java/

Setting a value for one of my instance variables isn't working

I'm trying to write a program that essentially evaluates a 5 card poker hand that is user-generated. One part of the program is that users can choose one variable to randomly change. The issue lies with setting a value for one of my instance variables, right now, my setCards, getCards, and changeOne methods are:
public void setCards(String str) {
this.cards = str;
calculateScore();
history = history + cards + score + changes;
changes++;
}
public String getCards() {
return this.cards;
}
public void changeOne(int pos) {
getCards();
calculateScore();
history = history + cards + score + changes;
randomChar = allCards.charAt((int)(Math.random()*cards.length()));
this.cards = cards.substring(0, pos) + randomChar + cards.substring(pos + 1, cards.length());
changes++;
}
In a separate class, I'm using:
cards = in.nextLine().toUpperCase();
myCards.setCards(cards);
I'm not sure why but whenever I try to use the changeOne method, keeps giving me the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 3, length 0
Which I assume is because it takes cards to be an empty string. I'm not sure what is happening and why it isn't getting the proper value of cards, help would be greatly appreciated.
Entire code:
First class:
import java.util.Scanner;
public class Assignment4{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
FiveCards myCards = new FiveCards();
int position;
String choice, cards;
char charChoice;
final char NEW = 'A';
final char CHANGE = 'B';
final char DISPLAY = 'C';
final char QUIT = 'Q';
do {
System.out.println("Choose (A: Make New Cards), (B: Change One Card), (C: Display Data), or (Q: Quit)");
choice = in.next();
charChoice = choice.toUpperCase().charAt(0);
switch(charChoice) {
case NEW:
System.out.println("*** Make New FiveCards ***");
System.out.println("Type five letters without space: ");
in.next();
cards = in.nextLine().toUpperCase();
myCards.setCards(cards);
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case CHANGE:
System.out.println("*** Change One Card ***");
System.out.println("Type one position to change (0-4): ");
position = in.nextInt();
myCards.changeOne(position);
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case DISPLAY:
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case QUIT:
System.out.println("*** End of Program ***");
break;
default:
System.out.println("Invalid input. Try Again");
break;
}
}while(charChoice!=QUIT);
}
}
Second class is:
public class FiveCards {
private String cards, history;
private int score, changes, counter;
private String allCards = "1234567890JQK";
private char randomChar;
public FiveCards() {
}
public void setCards(String str) {
this.cards = str;
calculateScore();
history = history + cards + score + changes;
changes++;
}
public String getCards() {
return this.cards;
}
public void changeOne(int pos) {
calculateScore();
history = history + cards + score + changes;
randomChar = allCards.charAt((int)(Math.random()*cards.length()));
this.cards = cards.substring(0, pos) + randomChar + cards.substring(pos + 1, cards.length());
System.out.println(cards);
changes++;
}
public void calculateScore() {
for(int i = 0; i<cards.length(); i++) {
for(int j = 0; j<cards.length(); j++) {
if((cards.charAt(i) == cards.charAt(j)) && (i != j)) {
counter++;
}
}
}
if(counter == 2) {
score = 1;
}
else if(counter == 4) {
score = 2;
}
else if(counter == 6) {
score = 3;
}
else if(counter == 8) {
score = 4;
}
else {
score = 0;
}
}
public String displayData() {
calculateScore();
history = history + cards + score + changes;
if(cards.length()<=1) {
return cards + " " + score + " " + changes;
}
else {
return "Empty" + " " + score + " " + changes;
}
}
}
First problem:
allCards.charAt(...). In the setCards you assign string to cards, but here you pick character from allCards. What is content of allCards? When it is assigned? I it assigned at all? (your code doesn't show this).
And the second problem:
Math.random()*cards.length()
Valid indexes of characters in the String are from 0 to length() - 1 inclusive, but the way you generate random index, you can give you index from 0 to length() inclusive. Change it to the Math.random()*(cards.length() - 1).

Connect 4 game exception handler for array In Java

I already finished my program it is a connect 4 console game the only problem is I don't know where should I place my ArrayIndexOutOfBoundsException in the code in order for it to this is what I want to put in the code
try {
int element = Input.nextInt();
System.out.println("Element in the given index is :: "+myArray[element]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("The index you have entered is invalid");
System.out.println("Please enter an index number between 0 and 6");
}
this is the game code it is made out of 3 classes
I'll post the game Engine for the program if it is not helpful I'll post the gameboard
public class C4GameEngine {
public static void main(String[] args) throws Exception {
String Start = "+------------------------------------------------------------------------------+\n" +
"| Welcome to Connect Four console application. |\n" +
"| Each player alternately drops a 'R' or 'Y' into one of the seven columns. |\n" +
"| The objective of the game is to connect four of the same characters in |\n" +
"| a row, column or diagonal. |\n" +
"+------------------------------------------------------------------------------+ ";
System.out.println(Start);
//We will use the scanner for using input have Input as reference variable
Scanner Input = new Scanner(System.in);
//making the red player enter their name
System.out.println("Red player enter your name: ");
String red = Input.nextLine();
//calling out the player class
PlayerClass p1 = new PlayerClass(red, "R");
//yellow player to enter their name
System.out.println("Yellow player enter your name: ");
String yellow = Input.nextLine();
//calling the player class for the yellow player
PlayerClass p2 = new PlayerClass(yellow, "Y");
// creating the while loop the purpose of it is to make the player decide if they want to keep playing
while (true) {
System.out.print("Do you want to keep playing? Type Y or N: ");
if (Input.nextLine().equalsIgnoreCase("Y")) {
//making the board game pattern and calling the connect four board
String[][] board = C4Board.createPattern();
boolean loop = true;
//in order to keep track of the turns
int count = 0;
C4Board.drawPattern(board);
while (loop) {
//this will let the red have the first turn then after every other turn yellow will play
if (count % 2 == 0) C4Board.dropRedPattern(board, p1.getName()); //getting the name
else C4Board.dropYellowPattern(board, p2.getName());
count++; //keeping track of the turns
C4Board.drawPattern(board);
if (C4Board.checkWinner(board) != null) {
//using the if statment to print out the winner if it is red
//one point will be set to red and then the question will repeat
//do you want to keep playing if you say Y you'll go back to the
//new game until you go with N it'll get out of the loop and show you the stats
if (C4Board.checkWinner(board) == "R") {
System.out.println("Red won.");
p1.setGameWon();
} else if (C4Board.checkWinner(board) == "Y") {
System.out.println("Yellow won.");
p2.setGameWon();
}
loop = false;
}
}
} else if (Input.nextLine().equalsIgnoreCase("N")) {
System.out.println(p1.toString());
System.out.println("--------------------");
System.out.println(p2.toString());
System.exit(0);
}
And now the gameboard
import java.util.Scanner;
//Creating the connect four board body
public class C4Board {
//We need to first create the basic visual pattern first using 2D array
public static String[][] createPattern() {
//creating a double array named field that will hold the length of array
String[][] field = new String[7][15];
// creating a loop for each row
for (int i =0;i<field.length;i++) {
// creating a loop for each column
for (int j =0;j<field[i].length;j++) {
if (j% 2 == 0){
//the column will be either empty or have a | depending on the disk
field[i][j] ="|";
} else {
field[i][j] = " ";
}
//creating the base for the row
if (i==6) field[i][j]= "-";
}
}
return field;
public static void drawPattern(String[][] f) {
for (int i =0;i<f.length;i++) {
for (int j=0;j<f[i].length;j++) {
System.out.print(f[i][j]);
}
System.out.println();
}
}
public static void dropRedPattern(String[][] f, String Name) {
//the first move would be is to have the User to tell us
//where he wants to drop the disk which column
System.out.println("+----------------------------------+\n");
//the Name String will display the end name of the user in game stat
System.out.print(Name + " drop a red disk at column (0–6):\n ");
System.out.println("+----------------------------------+\n");
//using it for keyboard input
Scanner Input = new Scanner (System.in);
int c = 2*Input.nextInt()+1;
for (int i =5;i>=0;i--) {
if (f[i][c] == " ") {
f[i][c] = "R";
break;
}
}
}
//this is the same as for the yellow disk
public static void dropYellowPattern(String[][] f, String Name) {
System.out.println("+----------------------------------+\n");
System.out.print(Name + " drop a Yellow disk at column (0–6):\n ");
System.out.println("+----------------------------------+\n");
Scanner scan = new Scanner (System.in);
int c = 2*scan.nextInt()+1;
for (int i =5;i>=0;i--) {
if (f[i][c] == " ") {
f[i][c] = "Y";
break;
}
}
}
//for the check winner in connect four you can win in many ways
//so there is going to be a for loop checking each of those
public static String checkWinner(String[][] f) {
//checking horizontal line
for (int i =0;i<6;i++) {
//the red or yellow disk or nothing will be in odd places
//we'll start from 0 (which will be 1) and stop at 6 (which will be 7)
for (int j=0;j<7;j+=2) {
if ((f[i][j+1] != " ")
&& (f[i][j+3] != " ")
&& (f[i][j+5] != " ")
&& (f[i][j+7] != " ")
&& ((f[i][j+1] == f[i][j+3])
&& (f[i][j+3] == f[i][j+5])
&& (f[i][j+5] == f[i][j+7])))
//returning the color if the pattern is the same
return f[i][j+1];
}
}
//vertical line looping over each odd column to check for repeated boxes in the same column
for (int i=1;i<15;i+=2) {
//we are vertically checking each line of the code now by the for loop statement so it's from 0 to 2
for (int j =0;j<3;j++) {
if((f[j][i] != " ")
&& (f[j+1][i] != " ")
&& (f[j+2][i] != " ")
&& (f[j+3][i] != " ")
&& ((f[j][i] == f[j+1][i])
&& (f[j+1][i] == f[j+2][i])
&& (f[j+2][i] == f[j+3][i])))
return f[j][i];
}
}
//For the diagonal line the loop has to go over the 3 uppermost rows
//then left to right column
for (int i=0;i<3;i++) {
for (int j=1;j<9;j+=2) {
//still using the odd index for the column and incrementing by 2
if((f[i][j] != " ")
&& (f[i+1][j+2] != " ")
&& (f[i+2][j+4] != " ")
&& (f[i+3][j+6] != " ")
&& ((f[i][j] == f[i+1][j+2])
&& (f[i+1][j+2] == f[i+2][j+4])
&& (f[i+2][j+4] == f[i+3][j+6])))
return f[i][j];
}
}
//this is the same as above but instead of going left to right we will go the opposing direction
for (int i=0;i<3;i++) {
for (int j=7;j<15;j+=2) {
if((f[i][j] != " ")
&& (f[i+1][j-2] != " ")
&& (f[i+2][j-4] != " ")
&& (f[i+3][j-6] != " ")
&& ((f[i][j] == f[i+1][j-2])
&& (f[i+1][j-2] == f[i+2][j-4])
&& (f[i+2][j-4] == f[i+3][j-6])))
return f[i][j];
}
}
//the null statement will return nothing if it doesn't find any disk anywhere
return null;
}
}

Having trouble solving logic of random number game

I am relatively new to java programming. I am currently working on building a mini guessing game, as a project to learn more Java. I am having some issues with the following:
Here are the 4 main things I am having trouble solving.
Record the answer for each user, if incorrect.
If the user was correct, skip them in subsequent rounds.
Once all players have guessed their correct number, print out the number of guesses it took for each one to guess correctly, the incorrect responses, and show a ranking of the players.
Ask if the user(s) wish to play again. If so, reset all values.
Here are the methods that I have written;
import java.io.*;
public class MultiPlayerRandomGame {
// this method asks how many users will be playing and returns the number of users
public static int howManyUsers() {
System.out.println("How many users will be playing?");
int players = IO.readInt();
return players;
}
// this method generates and returns a random number
public static int generateRandomNumber() {
int randomNumber = (int) (Math.random() * 100);
return randomNumber;
}
// this method compares user's entered guess and the generated random number then returns true/false
public static boolean compareGuess(int guess, int randomNumbers) {
boolean isGuessCorrect = false;
if (guess == randomNumbers) {
System.out.println("CORRECT!");
isGuessCorrect = true;
} else if (guess > randomNumbers) {
System.out.println("Too High");
} else if (guess < randomNumbers) {
System.out.println("Too Low");
}
System.out.println("test1");
return isGuessCorrect;
}
// this method determines whether Player N is correct or incorrect
public static boolean nextPlayer(int numOfUsers, int[] numberOfGuesses, int[] randomNumbers, int[][] numberBoard) {
for (int n = 0; n < numOfUsers; n++) {
int guessedNumber = numberOfGuesses[n];
/* if (guessedNumber == 0) {
return false;
}*/
if (numberBoard[n][guessedNumber] != randomNumbers[n]) {
return false;
}
}
return true;
}
/* this method is supposed to print out the number of guesses it took each player to guess their correct number
* CORRECTION: change the logic of this method to printing the number of guesses for one player then
* in the main method or wherever, make a for loop that prints out the number of guesses for each player
*/
public static void amountOfGuesses(int numOfUsers, int [] numberOfGuesses, int [][] numberBoard) {
int n = 0;
for ( int i = 0; i < numOfUsers; i++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[i]+ " time(s)");
}
}
// this method determines whether the user(s) would like to play again
public static boolean playAgain(String answer) {
boolean userWillPlayAgain;
if (answer.compareToIgnoreCase("no") == 0) {
userWillPlayAgain = false;
}
else {
userWillPlayAgain = true;
}
return userWillPlayAgain;
}
// this method controls the entire game
public static boolean playGame(){
boolean gameTerminate = false;
int numOfUsers = howManyUsers();
int [] randomNumbers = new int[numOfUsers];
int [] numberOfGuesses = new int [numOfUsers];
int [][] numberBoard = new int [numOfUsers][100];
// this for loop assigns the n random number(s) to the n player(s)
for (int n = 0; n < numOfUsers; n++){
randomNumbers[n] = generateRandomNumber();
System.out.println("PLAYER " + (n+1) + "'s RANDOM NUMBER: " + randomNumbers[n]);
}
do {
for (int i = 0; i < numOfUsers; i++) {
int guessedNumber = numberOfGuesses[i];
if (guessedNumber == 0 || numberBoard[i][guessedNumber-1] != randomNumbers[i]) {
System.out.println("Enter your guess Player " + (i+1) + ":");
int enteredGuess = IO.readInt();
numberBoard[i][guessedNumber] = enteredGuess;
numberOfGuesses[i] = guessedNumber + 1;
if(compareGuess(enteredGuess, randomNumbers[i])){
return true;
}
}
}
/* int n = 0;
* for ( int j = 0; j < numOfUsers; j++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[j]+ " time(s)"); }
*/
} while (nextPlayer(numOfUsers, numberOfGuesses, randomNumbers, numberBoard) == false);
// System.out.println("test");
return gameTerminate;
}
public static void main(String[] args){
boolean playing = true;
while (playing) {
playGame();
System.out.println("Would you like to play again?");
String answer = IO.readString();
playing = playAgain(answer);
}
System.out.println("OK, goodbye!");
}
}
Main issue as of right now: The game terminates and asks if user would like to play again after a player guesses their number, rather than after every player guesses their number.
Do I need actual Objects to make this happen and track every player or can this still be solved without objects? This is a territory I am unfamiliar with.
Right now your playGame method returns true back to main whenever any guess returns correct from compareGuess.
I would recommend setting up another array boolean[] correctGuess in playGame and mark the player number index as true if a player guesses correctly. You can use this new array to skip players who have guessed correctly, also. Once all players are marked true you can return to main.
This won't help improve your current code, but the same game can easily implemented using objects. In my opinion, the code is cleaner and easier to read.
Objects allow you to encapsulate the data required by each class. The target, number of guesses, and whether they were correct is stored in the Person object instead of in a multi-dimensional array. The values can be accessed by referencing the Person object - e.g. person.numGuesses or person.target.
By using objects, you can keep specific functionality scoped out of the main class. i.e. abstract away the implementation. In a future version of the game, you may want to change the way the target value is incremented; by using objects, the change can be made in the class which sets and checks the value - without affecting any other classes.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Game {
private final List<Person> personList = new ArrayList<>();
private Game(int numPlayers) {
for (int i = 0; i < numPlayers; i++) {
personList.add(new Person(i)); // Fill the player list
}
}
public static void main(String[] args) {
System.out.print("Enter the number of players: ");
Scanner sc = new Scanner(System.in);
int numPlayers = sc.nextInt();
// Initialise with the number of players
Game g = new Game(numPlayers);
g.mainLoop(); // Play the game
boolean playAgain = false;
do {
System.out.print("Do you wish to play again?: ");
String in = sc.next();
playAgain = "yes".equals(in);
if (playAgain) {
g.resetAll();
g.mainLoop();
}
} while (playAgain); // Only loop if they answered "yes"
}
private boolean allCorrect() {
// Check if all players have answered correctly
return personList.stream().allMatch(p -> p.correct);
}
private void resetAll() {
for (Person p : personList) {
p.reset(); // Reset each person
}
}
private void mainLoop() {
while (!allCorrect()) {
for (Person p : personList) {
p.doGuess(); // Ask for the guess
}
}
// Everyone is correct, print the scores.
for (Person p : personList) {
System.out.println("Player " + p.id + " => " + p.numGuesses + " guesses");
}
}
}
class Person {
final int id;
int numGuesses;
boolean correct;
private int target;
Person(int id) {
this.id = id;
target = new Random().nextInt(100); // Each player has a random target between 0-100
}
void doGuess() {
if (correct) {
// Skip turn if they're already correct
return;
}
numGuesses++;
System.out.print("Player " + id + " guess " + numGuesses + "(" + target + "): ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt(); // Read the guess
if (i == target) {
correct = true;
System.out.println("Correct!");
}
}
void reset() {
target = new Random().nextInt(100); // New target between 0-100
numGuesses = 0; // Reset the counter
correct = false;
}
}

Having trouble with this java code - supposed to print and count number of heads and tails in a random coin toss

So as the title says, I have to use a class file and also a main method java file that calls the class file and prints out the starting coin face, as well as 40 more coin face flips. I also need to have 2 counters that count the number of heads and number of tails. Here is my code for my class file and main method file. The problem I'm having is that whenever I run it, it always prints out that heads has 0 count and tails as 40 counts.
Class File:
import java.util.Random;
public class CoinToss
{
private String sideUp;
public CoinToss()
{
Random randomNum = new Random();
int number = randomNum.nextInt();
if(number%2 == 0)
sideUp = "heads";
else
sideUp = "tails";
System.out.println(sideUp);
}
public void toss()
{
Random randomNum = new Random();
int number = randomNum.nextInt();
if(number%2 != 0)
{
sideUp = "heads";
}
else
{
sideUp = "tails";
}
System.out.println(sideUp);
}
public String getSideUp()
{
return sideUp;
}
}
Main Method File
public class CoinTossDemo
{
public static void main(String[] args)
{
int headsCount = 0;
int tailsCount = 0;
System.out.print("The Starting side of the coin is: ");
CoinToss coin = new CoinToss();
System.out.println();
for(int x = 0; x < 40; x++)
{
System.out.print("The next side of the coin is: ");
coin.toss();
System.out.println();
if(coin.equals("heads"))
{
headsCount++;
}
else
{
tailsCount++;
}
}
System.out.println("The amount of heads that showed up is: " + headsCount);
System.out.println();
System.out.println("The amount of tails that showed up is: " + tailsCount);
}
}
Please help, thanks in advance.
Currently you're comparing the CoinToss coin object with the String value heads and that's why its always going to the else part.
I can see that you are setting the result of the current coin toss to sideUp(which is a String). Thus you need to compare that with the heads in the if.
if(coin.getSideUp().equals("heads")) { // getSideUp() returns the sideUp value
headsCount++;
} else {
tailsCount++;
}
You are assigning your answer to side up property so get that value coin.getSideUp()
for (int x = 0; x < 40; x++)
{
System.out.print("The next side of the coin is: ");
coin.toss();
System.out.println();
if (coin.getSideUp().equals("heads")) // use the side up property
{
headsCount++;
}
else
{
tailsCount++;
}
}

Categories