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;
}
}
Related
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/
I am currently attempting to finish my first coding Homework assignment, and My teacher and TA are utterly useless. I have been stuck on this problem and many more for days now with no response other than "There is an error" whenever I ask for help. When I try to run my code in Eclipse, it works perfectly and I have no errors that I have noticed. But, when I try to execute it from the cmd prompt I get the following message:
Exception in thread "main" java.lang.IllegalAccessException: Class org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader can not access a member of class ATM with modifiers "public static"
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
I have tried googling it, and as far as I have found, the Illegal Access Exception is thrown only for Private and Final methods, which I do not have any of in my code. Any help would be greatly appreciated! Also, please realize that my code may not be good as I have had to teach myself how to code completely.
import java.util.Scanner;
public class ATM {
static Scanner read = new Scanner(System.in); //created a scanner
static String inpCard;
static int listId = -1; //created an int to store the id of the place in which the ATMCard is stored under
static int withdrawlAMT = 0;
public static void main(String[] args) {
cardServices.initializeCardDB(); //enters the array's content
// asks for card number
if(cardServices.insertCard() == true) {
//checks for the pin to be correct
if(pin.processPin() == true) {
int x = account.select();
//if the account selected is checkings, it = 1.
if(x == 1) {
//asks user for how much to withdrawal.
money.moneyAmount();
// insures you dont have to little to withdrawal
// that much, loops forever if you try to withdrawal
// to much.
if(security.verifyBalCheck(withdrawlAMT) == true) {
cardServices.processCard(withdrawlAMT, "checking");
dispense.dispensing();
System.out.println("Your new balance is " +cardServices.cardList[listId].checkBal);
System.out.println("");
cardServices.returnCard();
}
}
//if the account selected is savings, it = 2.
if(x == 2) {
// asks user for how much to withdrawal
money.moneyAmount();
// insures you dont have to little to withdrawal
// that much, loops forever if you try to withdrawal
// to much.
if(security.verifyBalSaving(withdrawlAMT) == true) {
cardServices.processCard(withdrawlAMT, "savings");
dispense.dispensing();
System.out.println("Your new balance is " +cardServices.cardList[listId].savingsBal);
System.out.println("");
cardServices.returnCard();
}
}
}
}
}
}
class ATMBal
{
static int one = 50;
static int five = 40;
static int ten = 25;
static int twenty = 20;
static int total = 1000;
}
class ATMCard //Creating the blueprint for all cards
{
public String cardNum = " "; //Made both cardNum and cardPin to string, to avoid octal numbers
public String cardPin = " ";
public float checkBal = 0;
public float savingsBal = 0;
}
class cardServices
{
static ATMCard[] cardList = new ATMCard[5];
public static void initializeCardDB()
{
cardList[0] = new ATMCard();
cardList[0].cardNum = "123456789"; //added card 1's information
cardList[0].cardPin = "1111";
cardList[0].checkBal = 550;
cardList[0].savingsBal = 1275;
cardList[1] = new ATMCard();
cardList[1].cardNum = "135792468"; //added card 2's information
cardList[1].cardPin = "2097";
cardList[1].checkBal = 90;
cardList[1].savingsBal = -1;
cardList[2] = new ATMCard();
cardList[2].cardNum = "019283746"; //added card 3's information
cardList[2].cardPin = "6194";
cardList[2].checkBal = 7915;
cardList[2].savingsBal = -1;
cardList[3] = new ATMCard();
cardList[3].cardNum = "675849302"; //added card 4's information
cardList[3].cardPin = "0071";
cardList[3].checkBal = 790;
cardList[3].savingsBal = 211;
cardList[4] = new ATMCard();
cardList[4].cardNum = "347821904"; //added card 5's information
cardList[4].cardPin = "9871";
cardList[4].checkBal = 113;
cardList[4].savingsBal = 78;
}
public static boolean insertCard()
{
System.out.print("Please insert your card: "); //ask for card number
ATM.inpCard = ATM.read.nextLine(); //read card number
for(int i = 0; i < 5; i++) //start a loop
{
if(ATM.inpCard.compareTo(cardServices.cardList[i].cardNum) == 0) //checks all card numbers in the database, to see if they matched the input card
{
ATM.listId = i;
return true;
}
if(i == 4)
{
System.out.println("I'm sorry, your card was not found in our system.");
insertCard();
return false;
}
}
return false;
}
public static void processCard(int withdrawalAmount, String account) //actual process withdrawing the amount from the card
{
if(account.compareTo("checking") == 0)
cardServices.cardList[ATM.listId].checkBal = cardServices.cardList[ATM.listId].checkBal - withdrawalAmount;
if(account.compareTo("savings") == 0)
cardServices.cardList[ATM.listId].savingsBal = cardServices.cardList[ATM.listId].savingsBal - withdrawalAmount;
}
public static void returnCard() //returns the inpCard through a tempCard to insure all stored data is removed to increase security
{
System.out.println("Thank you for using Bank of America's new ACME ATMs, have a fantastic day!");
String tempCard = ATM.inpCard;
ATM.inpCard = null;
System.out.println("Here is your card: " +tempCard);
}
}
class pin
{
public static boolean processPin()
{
System.out.print("Please enter your pin number "); //asking for pin then read pin
String inpPinNum = ATM.read.nextLine();
for(int i = 0; i < 4; i++) //created loop
{
if(inpPinNum.compareTo(cardServices.cardList[ATM.listId].cardPin) == 0)
{
return true;
}
else
if(i < 3) //checks attempt amount to insure it is less than the allowed 4
{
System.out.println("Incorrect, please re-enter your pin:");
inpPinNum = ATM.read.nextLine();
}
if(i == 3) //if the pin has been incorrectly 4 times, the user is told that the card will be eaten
{
System.out.println("You have entered your pin incorrectly to many times,"
+ " your card is being destroyed. Please go to any Bank of America to recieve a new card");
eatCard(); //the eatCard() command is called to eat the card
}
}
return false;
}
public static void eatCard() //deletes the card in the system, without returning the card
{
ATM.inpCard = null;
}
}
class security
{
public static boolean verifyBalCheck(int withdrawlAmt) //checks checking balance
{
if(!(withdrawlAmt <=cardServices.cardList[ATM.listId].checkBal))
{
System.out.println("I'm sorry, you're current balance is: " +cardServices.cardList[ATM.listId].checkBal +", and as such you do not have enough to withdrawal that amount.");
money.moneyAmount();
return false;
}
return true;
}
public static boolean verifyBalSaving(int withdrawlAmt) //checks savings balance
{
if(!(withdrawlAmt <=cardServices.cardList[ATM.listId].savingsBal))
{
System.out.println("I'm sorry, you're current balance is: " +cardServices.cardList[ATM.listId].savingsBal +", and as such you do not have enough to withdrawal that amount.");
money.moneyAmount();
return false;
}
return true;
}
public boolean verifyMachineBalance(int withdrawlAmt) //checks ATM Machine Balance
{
if(withdrawlAmt <= ATMBal.total)
{
return true;
}
return false;
}
}
class account
{
public static int select()
{
System.out.print("Would you like to withdrawal from Checkings or Savings? ");
String type = ATM.read.nextLine();
if(type.compareToIgnoreCase("checkings") == 0) //checks to see if the string is checkings, returns 1 if so
{
return 1;
}
if(type.compareToIgnoreCase("savings") == 0) //checks to see if the string is savings, returns 2 if so
{
return 2;
}
return 0;
}
}
class money
{
public static void moneyAmount()
{
System.out.print("How much would you like to withdrawl? ");
ATM.withdrawlAMT = Integer.parseInt(ATM.read.nextLine());
}
}
class dispense
{
public static void dispensing()
{
ATMBal.total = ATMBal.total - ATM.withdrawlAMT; //removes the withdrawalAmt from total
System.out.println("");
System.out.println("Your total withdrawal amount is: " +ATM.withdrawlAMT);
while(ATM.withdrawlAMT >= 20 && ATMBal.twenty > 0) //checks to figure out the biggest bills the machine is able to dispense
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 20;
ATMBal.twenty = ATMBal.twenty - 1;
}
while(ATM.withdrawlAMT >= 10 && ATMBal.ten > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 10;
ATMBal.ten = ATMBal.ten - 1;
}
while(ATM.withdrawlAMT >= 5 && ATMBal.five > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 5;
ATMBal.five = ATMBal.five - 1;
}
while(ATM.withdrawlAMT >= 1 && ATMBal.one > 0)
{
ATM.withdrawlAMT = ATM.withdrawlAMT - 1;
ATMBal.one = ATMBal.one - 1;
}
int twenties = 20 - ATMBal.twenty; //Stoes how many of each will be dispensed
int tens = 25 - ATMBal.ten;
int fives = 40 - ATMBal.five;
int ones = 50 - ATMBal.one;
System.out.println("This is comprised of: " +twenties +" twenties, " //prints how much of each bill is being dispensed
+tens +" tens, "
+fives +" fives, and "
+ones +" ones");
}
}
i am having trouble passing the value of "guess" into my main method. The
method that is trying to return guess just shows up as zero in the main.I have tried various things such as void methods and different returns but the guess value does not get updated in the while loop of the main even though, from what i am seeing, it should be getting updated from the method and passing it down to the guesses right below it.
import java.util.*;
public class assignment052 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int userGuess = 0;
int compNum = 0;
int guess = 0;
int totalGuesses = 0; //
int best = 9999; //
introduction();
int games = 0;
String playAgain = "y";
while(playAgain.equalsIgnoreCase("y")) {
System.out.println();
System.out.println("I'm thinking of a number between 1 and 100...");
games++;
guessNumber(console, userGuess, compNum, guess);
System.out.println(guess);
totalGuesses += guess;
System.out.println("Do you want to play again?");
Scanner newGame = new Scanner(System.in);
playAgain = newGame.next();
if (best > guess) { //
best = guess; //
}
}
result(games, totalGuesses, best);
}
// Method that introduces the game
public static void introduction() {
System.out.println("This program allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println("100 and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
}
// method to play 1 game
public static double guessNumber(Scanner console, int userGuess, int compNum, int guess) {
Random rand = new Random();
userGuess = console.nextInt();
guess = 1;
compNum = rand.nextInt(100)+1;
while(compNum != userGuess) {
if(compNum > userGuess) {
System.out.println("It's higher.");
} else {
System.out.println("It's lower.");
}
guess++;
userGuess = console.nextInt();
}
System.out.println("you got it right in " + guess + " guesses");
return guess;
}
// method for overall result
public static void result(int games, int totalGuesses, int best) {
System.out.println("Overall results:");
System.out.println();
System.out.println("Total games played : " + games);
System.out.println("Total guesses : " + totalGuesses);
System.out.println("Guesses per game : " + totalGuesses / games);
}
}
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"))
I am making a lottery application in Java. My problem is that I think everything is in place and it (the IDE) is telling me that "int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;" needs to be static. So I change it to a static int and then I have to change it again in my class. Problem is when I finally run it I get all 0's for my random lottery data. Please help me find the errors in my ways. Total newb here and I've been looking online here but I want to try to figure it out without just copying code somewhere.
Eck_LotteryClass
import java.util.Random;
public class Eck_LotteryClass {
//instance field
private int lotteryNumbers [];
//Create random lottery numbers method array
public int [] getRandomNumbers(){
lotteryNumbers = new int [5];
Random r = new Random();
for(int i = 0; i < 5; i++)
lotteryNumbers[i] = r.nextInt(10);
return lotteryNumbers;
}
public int compareNumbers(int[] usersNumbers) {
int matchedNums = 0;
if (usersNumbers.length == lotteryNumbers.length) {
for (int i = 0; i < lotteryNumbers.length; i++) {
if (usersNumbers[i] == lotteryNumbers[i]) {
matchedNums ++;
}
}
}
return matchedNums;}
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return lotteryNumbers;
}
}
Eck_LotteryTester
import java.util.Scanner;
import java.util.Arrays;
public class Eck_LotteryTester{
public static void main(String[] args) {
Eck_LotteryClass lottery = new Eck_LotteryClass();
int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;
System.out.println("The Pennsylvania Lottery\n");
System.out.println("There are " + lotteryNumbersCount
+ " numbers in my lottery, they are 0 through 9. "
+ "See if you can win big CASH prizes!!!\n");
// Asks the user to enter five numbers.
Scanner keyboard = new Scanner(System.in);
int numbers[] = new int[lotteryNumbersCount];
for (int index = 0; index < numbers.length; index++) {
System.out.print(String.format("Enter Number %d: ", index + 1));
numbers[index] = keyboard.nextInt();
}
// Display the number of digits that match the randomly generated
// lottery numbers.
int match = lottery.compareNumbers(numbers);
if (match == lotteryNumbersCount) {
// If all of the digits match, display a message proclaiming the
// user a grand prize winner.
System.out.println("\nYOU WIN, GO SEE D. LEETE FOR YOUR GRAND PRIZE!!!");
} else {
System.out.println("\nThe winning numbers are " + Arrays.toString(Eck_LotteryClass.getLotteryNumbers()) +
"\nYou matched " + match + " number(s).");
}
}
}
Change
int lotteryNumbersCount = Eck_LotteryClass.getLotteryNumbers().length;
to
int lotteryNumbersCount = lottery .getLotteryNumbers().length;
and you won't have to change the methods signature to static. Also you'll be talking about the same variable.
Also change
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return lotteryNumbers;
}
to
// Display the random lottery numbers for the user
public int [] getLotteryNumbers() {
return getRandomNumbers();
}
So the array gets initialized. And changing the signature of
public int [] getRandomNumbers
to
private int [] getRandomNumbers
wouldn't hurt
package New_list;
import java.util.Scanner;
import java.util.Random;
public class Lottery {
private static Scanner scan;
public static void main(String[] args) {
System.out.println("\t\t\tWelcome to Harsh Lottery System.\n");
Random random = new Random();
int lottery_win_1 = random.nextInt(10);
// Print Lottery winning number...1 :P
// System.out.println(lottery_win_1 + "\n");
int lottery_win_2 = random.nextInt(10);
// Print Lottery winning number...2 :P
// System.out.println(lottery_win_2 + "\n");
boolean loop = true;
while(loop){
System.out.println("\t\t\tEnter your 2 Digit Lottery number.\n");
scan = new Scanner(System.in);
int lottery_no = scan.nextInt();
if ((lottery_no >= 0) && (lottery_no <= 99)) {
int lottery_no_1, lottery_no_2;
if (lottery_no > 9) {
lottery_no_1 = lottery_no / 10;
lottery_no_2 = lottery_no % 10;
} else {
lottery_no_1 = 0;
lottery_no_2 = lottery_no;
}
if ((lottery_win_1 == lottery_no_1)
&& (lottery_win_2 == lottery_no_2)) {
System.out
.println("\t\t\tCongratulation you win lottery,and you win $10000.\n");
} else if ((lottery_win_1 == lottery_no_2)
&& (lottery_win_2 == lottery_no_1)) {
System.out
.println("\t\t\tCongratulation your inverse no is lottery winer number so that you win $4000.\n");
} else if ((lottery_win_1 == lottery_no_1)
|| (lottery_win_1 == lottery_no_2)
|| (lottery_win_2 == lottery_no_1)
|| (lottery_win_2 == lottery_no_2)) {
System.out
.println("\t\t\tCongratulation your one digit from your lotter number match to the lottery winner.so you win $1000.\n");
} else {
System.out.println("\t\t\tSorry,Please try again\n");
System.out.println("\t\t\tDo you want to try again\n\t\t\tPress 1 for Continue\n\t\t\tPress 2 for exit\n");
int ch = scan.nextInt();
switch(ch){
case 1: System.out.println("\t\t\tOk...Try again\n");
break;
case 2: System.out.println("\t\t\tBbye... See you later\n");
loop = false;
break;
}
}
} else {
System.out.println("\t\t\tSorry,Please choose 2 digit number\n");
}
}
}
}