Java: Hangman game, 10 chances, but only 5 lives - java

I'm creating a little mini game of Hangman. The user has 10 chances to guess, but only 5 lives.
The app works, but will continue after the 5th life, even though, I was hoping it would throw the player out of that loop.
The instantiable class (Hangman.java) is working without problems.
The secret word is "julie" as described in the instantiable class.
My App class:
import javax.swing.JOptionPane;
public class HangmanApp {
public static void main(String args[]) {
String input, secret, result, playAgain;
char guess;
int i, j, k, lives;
Hangman myHangman = new Hangman();
do{
JOptionPane.showMessageDialog(null, "Hello, welcome to Hangman! You have 10 chances but only 5 lives! Best of luck");
lives = 5;
for (j = 10; j > 0; j--) {
while (lives >= 0){
input = JOptionPane.showInputDialog(null, "Please enter a letter");
guess = input.charAt(0);
//process
myHangman.setGuess(guess);
myHangman.compute();
result = myHangman.getResult();
if ((input.charAt(0) == 'j') || (input.charAt(0) == 'u') || (input.charAt(0) == 'l') || (input.charAt(0) == 'i') || (input.charAt(0) == 'e')) {
JOptionPane.showMessageDialog(null, "That letter is in the word! Current correct letters: " + result + ".");
} else {
lives--;
JOptionPane.showMessageDialog(null, "Sorry, that letter is not there. Current correct letters: " + result + ".");
}
//output
//JOptionPane.showMessageDialog(null, "Current correct letters: " + result);
};
lives = -1;
}
result = myHangman.getResult();
secret = myHangman.getSecret();
if (secret.equals(result)) {
JOptionPane.showMessageDialog(null, "Congratulations, you got it!! The word was " + secret + ".");
} else {
JOptionPane.showMessageDialog(null, "Sorry, you didn't get it, better look next time! The word was " + secret + ".");
}
playAgain = JOptionPane.showInputDialog("Do you want to play again? yes/no");
}while (playAgain.equals("yes"));
}
}

Try the following change:
while (lives > 0){
you start at 5 and then go down to 4 3 2 1 AND 0. with the change this will stop at 0

// don't need two nested cycles, you can do it in a single one
// The cycle exits if any one of the conditions fail
// max attempts exhausted or all the lives are lost
// -------------------v v------------------------
for (j = 10, lives=5; j > 0 && lives > 0 ; j--) {
// -------------------------------------^
// j - the number of attempt is decremented for each trial,
// no matter if successful or not
//... the rest of cycle logic, which will decrement the lives
// only in cases of unsuccessful attempts
}

Related

While loop with JOptionPane returning StringIndexOutOfBounds Exceptions

In my code I have a while loop with 3 IF tests nested in between that have flags triggered by ELSE:
[test1] checks whether the input value has a length of exactly 1 [Prevents users from inputting nothing]
[test2] checks whether the input value at index 0 is a digit [I need a number as an input, but I'm using JSWING]
[test3] checks whether the input value length is greater than 1 [2 Digits (10,11,12,...)
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
while(exit == false || test1 == false || test2 == false || test3 == false) {
if(num1.length() < 1) {
JOptionPane.showMessageDialog(null,"Input required");
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
}
else {
test1 = true;
}
if(Character.isDigit(num1.charAt(0)) == false) {
JOptionPane.showMessageDialog(null,"Input has to be a number between 0 - 9.");
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
}
else {
test2 = true;
}
if(num1.length() > 1) {
JOptionPane.showMessageDialog(null,"Input has to be a number between 0 - 9.");
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "0");
}
else {
test3 = true;
}
if(test1 == true && test2 == true && test3 == true) {
exit = true;
}
The problem I'm having is somewhere between the first and second test. When I try inputting nothing as a value ["" / or just having an empty box and pressing enter], it detects the error of having nothing and displays "Input required" once, but once it loops, it outputs a StringIndexOutOfBoundsException for the second trial
It works in every other case I've tried (no input -> correct, no-input -> incorrect...) Only sequential no-input cases crash the program.
The error is said to be in this line, but I don't understand where, or how.
if(Character.isDigit(num1.charAt(0)) == false)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at oof.Lottery_Swing_FIX.main(Lottery_Swing_FIX.java:56)
Fixed Logic
JOptionPane.showMessageDialog(null,"Enter 3 one-digit positive numbers for your 3 guesses");
for(int counter = 0; counter < LIMIT; counter++) {
test = false;
while(exit == false || test == false) {
num1= JOptionPane.showInputDialog(null,"Please input Guess #" + (counter+1), "");
if(num1.length() < 1 || Character.isDigit(num1.charAt(0)) == false || num1.length() > 1) {
JOptionPane.showMessageDialog(null,"Integer between 1-9 required");
}
else {
test = true;
}
if(test == true) {
numberInput = Integer.parseInt(num1);
exit = true;
}
else {
continue;
}
}
Your 'fix' doesn't handle null which will be returned by the JOptionPane.showInputDialog() if the dialog is closed (x) or the cancel Cancel button is selected. You can't play null against the String#length() method as you can with a Null String ("") so, you need to check for this in your code otherwise you can end up with a NullPointerException. You can do this in your very first if statement as a conditional component:
if (num1 == null) {
// The CANCEL or dialog close button was selected.
}
You really don't need those boolean flags in your code. Things are going to happen or they simply will not. You don't really need flags to remind you so close to home (so to speak). If you have the conditions established properly within the if statements and utilize else if then they're not required. With that being said, you don't need these boolean flags within the condition for the while loop either.
The while loop needs to be concerned about one thing...that the prompt is provided valid data. If it isn't then the variable (num1) which holds the prompt data is converted to a null string (""). So in reality:
String num1 = "";
while (num1.equals("")) { .... }
So, for as long as num1 contains a null string ("") we just keep looping thus re-prompting for proper input.
In your code, you want to provide the User with specific details as to why their input failed. There are several ways to do this however whichever way you choose to do it, make sure it doesn't generate any exceptions (errors) that can ultimately halt your application or change its accurate performance. There is nothing wrong with using if and else if statements to carry out this particular task in its current use-case. Following your particular theme:
int LIMIT = 3, numberInput;
int[] guesses = new int[LIMIT];
String errMsg;
String num1;
JOptionPane.showMessageDialog(null, "<html>You will be prompted three times "
+ "to supply<br>a positive <font color=red><b>single digit</b></font> "
+ "number.</html>", "Information", JOptionPane.INFORMATION_MESSAGE);
for (int counter = 0; counter < LIMIT; counter++) {
num1 = "";
while (num1.equals("")) {
errMsg = "";
num1 = JOptionPane.showInputDialog(null, "Please input Guess #" + (counter + 1),
"Guess #" + (counter + 1),JOptionPane.QUESTION_MESSAGE);
// Does num1 contain null?
if (num1 == null) {
if (JOptionPane.showConfirmDialog(null,
"<html>You <font color=blue>canceled</font> your input!<br>"
+ "Do you want to quit?</html>", "Quit",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
System.exit(0);
}
num1 = ""; // Set for re-prompt.
continue;
}
// Is nothing supplied?
else if (num1.length() < 1) {
errMsg = "<html><font size=5 color=red><center>Nothing Supplied!"
+ "</center></font><br>You must provide a single Integer "
+ "value between<br>0 and 9 (inclusive).</html>";
}
// Is too much supplied?
else if (num1.length() > 1) {
errMsg = "<html><center><font size=5 color=red>To Much Supplied!</font><br>" +
"<font size=5 color=blue>\"" + num1 + "\"</font></center><br>" +
"You must provide a single Integer value between<br>0 and 9 "
+ "(inclusive).</html>";
}
// Is the supplied character a number?
else if (!Character.isDigit(num1.charAt(0))) {
errMsg = "<html><center><font size=5 color=red>Invalid Digit Supplied!"
+ "</font><br><font size=5 color=blue>\"" + num1 + "\"</font>"
+ "</center><br>You must provide a single Integer value "
+ "between<br>0 and 9 (inclusive).</html>";
}
// Does errMsg actually contain a message? If so display it.
if (!errMsg.equals("")) {
JOptionPane.showMessageDialog(null, errMsg, "Invalid Input!",
JOptionPane.WARNING_MESSAGE);
num1 = ""; // Set for re-prompt.
}
else {
numberInput = Integer.parseInt(num1);
// ... do whatever you want to do with numberInput, for example ....
guesses[counter] = numberInput;
}
}
}
// Display User's LIMITED guesses:
StringBuilder sb = new StringBuilder();
sb.append("<html>The <font color=red><b>").append(LIMIT).
append("</b></font> Guesses supplied by User are:<br><br>");
for (int i = 0; i < guesses.length; i++) {
sb.append("Guess #").append((i + 1)).append(": <font color=blue>").append(guesses[i]).append("</font><br>");
}
sb.append("</html>");
JOptionPane.showMessageDialog(null, sb.toString(), "Guesses Provided",
JOptionPane.INFORMATION_MESSAGE);
As you can see, providing details to a User about input failures requires a lot more code. All this code can be removed if you decide you want just a simple "Invalid Input!" message. This in essence forces the User to read the supplied prompts with more intensity, for example:
int LIMIT = 3;
int numberInput;
int[] guesses = new int[LIMIT];
String num1;
JOptionPane.showMessageDialog(null, "<html>You will be prompted three times "
+ "to supply<br>a positive <font color=red><b>single digit</b></font> "
+ "number.</html>", "Information", JOptionPane.INFORMATION_MESSAGE);
for (int counter = 0; counter < LIMIT; counter++) {
num1 = "";
while (num1.equals("")) {
num1 = JOptionPane.showInputDialog(null, "Please input Guess #" + (counter + 1),
"Guess #" + (counter + 1),JOptionPane.QUESTION_MESSAGE);
// Does num1 contain null?
if (num1 == null){
if (JOptionPane.showConfirmDialog(null,
"<html>You <font color=blue>canceled</font> your input!<br>"
+ "Do you want to quit?</html>", "Quit",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
System.exit(0);
}
num1 = ""; // Set for re-prompt.
}
else if (!num1.matches("\\d")) {
JOptionPane.showMessageDialog(null, "<html><center><font size=5 color=red>Invalid Input Supplied!</font><br>" +
"<font size=5 color=blue>\"" + num1 + "\"</font></center><br>" +
"You must provide a single Integer value between<br>0 and 9 "
+ "(inclusive).</html>", "Invalid Input!", JOptionPane.WARNING_MESSAGE);
num1 = "";
}
else {
numberInput = Integer.parseInt(num1);
// ... do whatever you want to do with numberInput, for example ....
guesses[counter] = numberInput;
}
}
}
// Display User's LIMITED guesses:
StringBuilder sb = new StringBuilder();
sb.append("<html>The <font color=red><b>").append(LIMIT).
append("</b></font> Guesses supplied by User are:<br><br>");
for (int i = 0; i < guesses.length; i++) {
sb.append("Guess #").append((i + 1)).append(": <font color=blue>").append(guesses[i]).append("</font><br>");
}
sb.append("</html>");
JOptionPane.showMessageDialog(null, sb.toString(), "Guesses Provided",
JOptionPane.INFORMATION_MESSAGE);
Pay special note to the condition for the else if statement (!num1.matches("\\d)) in the above code. Here the use of the String#matches() method is used with a small Regular Expression, the "\\d" expression. This expression tells the matches() method to see if the string we're matching (in num1) is a single digit string numerical value (like: "5" for example). So, what the else if statement is asking:
else if the string contained in num1 is NOT (!) a single digit string numerical value then run the code in my curly braces ({...}). This basically covers all input failures except null (because we're handling that as a quit option) and the String#matches() method will not accept null.
If you don't want a quit option then then you would only need a single if statement in your code:
if (num1 == null || !num1.matches("\\d")) { ... }

do while loop syntax error, program not going through all of code, code efficiecy [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I made a basic number guessing game, everything was working fine until i tried to add a "play again" feature at the end of it. When the program is run, after inputting the first guess, it just starts the loop over again without going through the rest of it. Also, I am unsure if my code is efficient or not. It seems like too much coding for a simple concept. Is this an average length for a basic guessing program? Sorry if my questions are worded strangely. I'm a first year college student just learning the basics of programming. Here is my code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random randomNum = new Random();
boolean playing = true;
do {
int max = 100;
int min = 1;
int counter = 10;
int guess = 0;
int guessThis = min + randomNum.nextInt(max);
System.out.println("I'm thinking of a number between 1 and 100. You have 10 tries to guess it. What's your first guess?");
guess = input.nextInt();
counter--;
if (guess == guessThis) {
playing = false;
} else {
playing = true;
}
if (guess > max) {
System.out.println("I said the number is between 1 and 100. You think this is a GAME MUTHA FUCKA??! Guess again... :) " + counter + " guesses left.");
}
if (min > guess) {
System.out.println("Bruh. Are you stupid? " + guess + " is not between 1 and 100. Try again dummy boi. " + counter + " guesses left.");
}
if (guess > guessThis && min <= guess && guess >= max && playing == true && counter > 0) {
System.out.println("Too high. Guess again. " + counter + " guesses left.");
} else if (guess < guessThis && min <= guess && guess >= max && playing == true && counter >0) {
System.out.println("Too low. Guess again. " + counter + " guesses left.");
}
if (playing == false && counter > 0) {
System.out.println("You guessed it!");
}
if (counter <= 0) {
System.out.println("You lose! Ha! Fuck off broooooo. My number was " + guessThis);
playing = false;
}
}while (playing == true);
String answer;
if (playing == false) {
System.out.println("Wanna play again? (y/n)");
}
answer = input.next();
if (answer == "n") {
System.out.println("My game isn't fun enough for you? Wow, okay, rude. Bye then. Dh.");
input.close();
} if (answer == "y") {
playing = true;
}
}
}
use
}while (playing == true);
after the end of if statement
if (answer == "y") {
playing = true;
}

How to make int counter go down when answer is wrong

Im making a player 2 guesses player 1's number game. Ive made an int counter thats == 10 and is meant to go down everytime player 2 gets answer wrong. I cant get it to work and i need help on how to make this. Youll see what i mean...
package guessMain;
import java.awt.*;
import java.util.Scanner;
public class GuessCodeSource {
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else if (answer <= 100){
System.out.println("Guess in the space below.");
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
}else if (guess != answer);
for (int counter = 10; counter-=1);
System.out.println("You have " + count + " of guesses left");
}
}
}
To make reduce a number by one, use the decrement operator.
For example,
counter--;
would subtract one from the counter.
If you want to subtract more than one, you can use the "-=" operator in the following manner:
counter -= 2;
So, in your code, in the final else if block, you could change the code to the following to reduce "counter" by 1.
else if (guess != answer) {
counter--;
System.out.println("You have " + count + " of guesses left");
}
But, in your code, you never declare the variable counter. Somewhere, most likely at the top of your code, you want to create this variable. To create an Integer variable you do the following:
int counter = 10;
You asked how to LOOP as well, so here it is. Read the comments to gain understanding of what the code does. If you have more questions, ask below.
public static void main(String[] args) {
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
int guess = 0; // Create these variables up here to access them everywhere in "main"
int counter = 0;
boolean continueTheGame = true; // A boolean variable that holds ONLY either true or false
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
// A while loop will continue as long as a boolean expression is true.
// So, we create a boolean variable somewhere above called "continueTheGame"
// As long as this is true, the code INSIDE of the while loop's brackets will repeat.
// If the user has less than zero guesses left, we can set the variable to false,
// which will make the loop stop!
while (continueTheGame == true) { // The start of the while loop
if (answer >= 100) {
System.out.println("BUSTED! I said a number between 1 - 100!");
} else if (answer <= 100) {
System.out.println("Guess in the space below.");
guess = josh.nextInt();
}
if (guess == answer) {
System.out.println("CORRECT!!!!!");
} else if (guess != answer) {
counter--;
System.out.println("You have " + counter + " of guesses left");
if (counter > 0) { // If they have MORE than zero guesses left, loop again!
continueTheGame = true;
} else { // If they have zero guesses left, make it stop looping
continueTheGame = false;
}
}
}
// Once the loop ends, the code will start again here,
// because the bracket above is the final bracket of the WHILE loop
}
Okay, so here is the full functional main method you are looking for:
public static void main(String[] args){
System.out.println("WELCOME TO GUESSING GAME BY JOSH!");
System.out.println("Rules: Player 1 picks number between 1 - 100 while Player 2 has 10 tries to guess");
Scanner josh = new Scanner(System.in);
System.out.println("Enter name here PLAYER 1: ");
String p1 = josh.nextLine();
System.out.println("Enter name here PLAYER 2: ");
String p2 = josh.nextLine();
System.out.println("Ok, " + p2 + " look away. " + p1 + ", Please enter a number and press enter:");
int answer = josh.nextInt();
if (answer >= 100){
System.out.println("BUSTED! I said a number between 1 - 100!");
}else {
System.out.println("Guess in the space below.");
}
for (int count = 10; count>=0; count--) {
int guess = josh.nextInt();
if (guess == answer){
System.out.println("CORRECT!!!!!");
System.exit(0);
} else {
System.out.println("You have " + count + " of guesses left");
if (count == 0) {
System.out.println("Sorry, you lost, no more tries..");
System.exit(0);
}
}
}
josh.close();
}

Why is this code not working? Hangman

I am creating a hangman game. Everything works fine, I have code ready to be used for failing the game and giving -1 to the guesses. Though when adding it to the else statement it gets duplicate equal to the length of the word and it also gives a guess—even though its right? I don't see what's wrong in the code? I believe it's my code when guessing wrong which is not placed right though I see no other way?
This is the code:
private class check implements ActionListener {
public void actionPerformed(ActionEvent ae) {
try {
// Grabs the letter from the guessField and converts it into a char
// which can be used to compare against the word.
guess = guessField.getText();
guessField.setText("");
char guess2 = guess.charAt(0);
// --------------------
// Here is the guessing logic but it's currently
// not working and you can not win since i haven't written code for
// it yet. it's not selecting all the letters. for Example if
// choosing A in a word such as Banana it only selects the first
// a--------------------------- //
String displaySecret = wordField.getText();
if (displaySecret.equals("")) {/* case for fist execution */
displaySecret = "";
for (int i = 0; i < random.length(); i++)
displaySecret += "_ ";
}
String newDisplaySecret = "";
for (int v = 0; v < random.length(); v++) {
if (guess2 == random.charAt(v)) {
newDisplaySecret += random.charAt(v); // newly guessed
// character
} else {
newDisplaySecret += displaySecret.charAt(v); // old state
guesses--;
statusLabel.setText("Guesses left: " + guesses);
missField.setText(missField.getText() + guess);
if (guesses <= 0) {
JOptionPane.showMessageDialog(null,
"Game over! The word was: " + random);
guessField.setEditable(false);
wordField.setText("");
missField.setText("");
guesses = 7;
statusLabel.setText("Guesses left: " + guesses);
}
}
}
displaySecret = new String(newDisplaySecret);
wordField.setText(displaySecret);
if (displaySecret.equals(random)) {
JOptionPane.showMessageDialog(null, "You Won! The Word was: "
+ random);
guesses = 7;
statusLabel.setText("Guesses left: " + guesses);
wordField.setText("");
missField.setText("");
guessField.setEditable(false);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
If randomis your Word, you iterate over each Character of it and then check whether each single character matches the guess you get for each character that doesn't match the guess a -1.
For Example: The Word is Bananaramaand you guess a nyour first and second matches will go to the else clause. then one time the if clause goes again, then the else and so on.
You have to
iterate over all characters, check whether they match or not
if a match occurs, replace the char and increase the counter
check if the counter of correct characters equals 0
if so, decrease the guesses
Some other tips: you should use .toLower() on your input and word string before comparsion to allow insensitivity for case
Some sample code:
int charsGuessedCorrectly;
for ( int i = 0; i < random.length( ); i++ )
{
if ( random.charAt( i ) == guess )
{
charsGuessedCorrectly++;
newDisplaySecret += random.charAt(v); // newly guessed
// character
}
}
if ( charsGuessedCorrectly == 0 )
{
newDisplaySecret += displaySecret.charAt(v); // old state
guesses--;
statusLabel.setText("Guesses left: " + guesses);
missField.setText(missField.getText() + guess);
if (guesses <= 0) {
JOptionPane.showMessageDialog(null,
"Game over! The word was: " + random);
guessField.setEditable(false);
wordField.setText("");
missField.setText("");
guesses = 7;
statusLabel.setText("Guesses left: " + guesses);
}
Here is what you need to check your word and generate "newDisplaySecret":
for (int v = 0; v < random.length(); v++) {
if (guess2 == random.charAt(v)) {
newDisplaySecret += random.charAt(v); // newly guessed
// character
} else {
newDisplaySecret += displaySecret.charAt(v);
}
Here is how you can determine whether the player guessed right or wrong:
if(newDisplaySecret.equals(displaySecret)){
guesses --;
}
This needs to be placed after your check word code. Your code seems to decrement guesses for each letter in the word random.
Update display:
displaySecret = new String(newDisplaySecret);
wordField.setText(displaySecret);
Now that you know what the current state of affairs is for this move you can decide if the person has won or lost or just needs to continue playing:
if(guesses <= 0){
/*place here instructions for loosing scenario*/
}else{
if(displaySecret.equals(random)) {
/*place here instructions for winning scenario*/
}
/*simply do nothing the game is neither lost or won*/
}
Hope this helps

Java while loop and other

I need help I am new to Java programming and I don't know how to fix my code.
I am trying to make a 007 game. I have created the if statements and it isn't looping around. If I add a ! in front of the each statement in the do-while loop it causes a infinity loop.
How can I fix my programming.
import java.util.Scanner;
import java.util.Random;
public class DoubleOSeven {
public static void main(String[] args) {
System.out.println("Let's Play a game of 007 ");
System.out.println("You can SHOOT, BLOCK, AND RELOAD");
System.out.println("Both you and I start with one bullet");
Scanner input = new Scanner(System.in);
System.out.println("Let's Start, Enter (shoot, reload , or block) ");
String INput = input.nextLine();
//User and Computer ammo
int Userammo = 1;
int ammo = 1;
//Creates a random number between 1 and 3
Random rand = new Random();
int output = rand.nextInt(3) + 1;
do{
//User chooses shoot
if(INput.equals("shoot")){
Userammo --;
System.out.println("You took a shot, Your ammo count is at: " + Userammo);
//User chooses reload
}else if (INput.equals("reload")){
Userammo ++;
System.out.println("You reloaded, Your ammo count is at: " + Userammo);
//User chooses block
}else if(INput.equals("block")){
System.out.println("You blocked, Your ammo count is at: " + Userammo);
//If random is 1 shoot
}if(output == 1){
ammo ++;
System.out.println("I took a shot at you, My ammo count is at: " + ammo);
//If random is 2 block
}else if(output == 2){
System.out.println("I blocked, My ammo count is at: " + ammo);
//If random is 3 reload
}else if(output == 3){
ammo ++;
System.out.println("I reloaded, My ammo count is at: " + ammo);
//If both User and Computer shoot
}if(output == 1 && INput == "shoot"){
System.out.println("It's a tie you we both die");
}
}while((output == 3 && INput == "shoot") && (output == 1 && INput == "reload") && (output == 1 && INput == "shoot"));
}
}
while((output == 3 && INput == "shoot") && (output == 1 && INput == "reload") && (output == 1 && INput == "shoot"));
should be
while((output == 3 && INput.equals("shoot")) || (output == 1 && INput.equals("reload")) || (output == 1 && INput.equals("shoot")));
First of all: In order for the loop to work well, the question to the user and the computer random decision have to be inside the loop. In this way each loop has a new set of values for the variables.
// Declare variables
String INput = "";
Random rand = new Random();
int output = 0;
do{
// Ask user
System.out.println("Enter (shoot, reload , or block) ");
INput = input.nextLine();
// Computer decision
output = rand.nextInt(3) + 1;
...
Second: You need to have an explicit decision when to terminate the loop (ie the game). This can be done with one of the following
the user wants to end the game (that needs one more option quit in the user choices)
the computer wants to end the game (that needs a forth random number that means quit).
some condition from the combination of user/computer ammo and user/computer shoot. That is you can end the game if some player is shot and has zero ammo.
In all these cases you need to
declare a variable for the end of the game before the loop
decide what to do in the loop
continue the loop if not end of game
This is snippet for this:
boolean endOfGame = false;
...
do {
...
if ( INput.equals("quit")
|| (INput.equals("shoot") && ammo == 0)
|| (Userammo == 0 && output == 1) ) {
endOfGame = true;
}
...
} while (!endOfGame);
You could have the same efect if you put the decision in the while,
but in this way the decision for the end of game is more clear.
It is also possible to set the endOfGame to true in many different places in the loop.
Edit: Some notes on coding style etc
It is a common good practice the names of the variables to start with low case letters (eg instead of Userammo use userAmmo). Names starting with capital letters denote classes.
It makes the code easier to read if the names have some meaning. For example I would suggest the following changes for some of your variables
INput → userAction
Userammo → userAmmo
output → compAction
ammo → compAmmo
Use final constants to give meaning to numbers or strings that appear in your code repeatedly.
Start the if statement on a new line. (else if on the same line is ok)
Using these you could have written (and some comments are not needed)
public class DoubleOSeven {
public static final String S_SHOOT = "shoot";
public static final String S_BLOCK = "block";
public static final String S_RELOAD = "reload";
public static final int I_SHOOT = 1;
public static final int I_BLOCK = 2;
public static final int I_RELOAD = 3;
...
System.out.println("Enter ("+ S_SHOOT + ", " + S_RELOAD + " or " + S_BLOCK + ") ");
...
} else if(userAction.equals(S_BLOCK)){
System.out.println("You blocked, Your ammo count is at: " + userAmmo);
}
if(compAction == I_SHOOT){
compAmmo--; // I changed ++ to -- in order to be a fair game
System.out.println("I took a shot at you, My ammo count is at: " + compAmmo);
} else if(compAction == I_BLOCK){
System.out.println("I blocked, My ammo count is at: " + compAmmo);
...
As per your condition as below
while((output == 3 && INput == "shoot") && (output == 1 && INput == "reload") && (output == 1 && INput == "shoot"));
the loop will be executed only if the 3 conditions are true.
You need to make some changes in your condition
All your && cases that are evaluated for this loop result in a false.
Let's say, T for all true cases and F for all F cases
If T&&T&&T then yes we = T (the case for adding !)
If T&&F&&F then F
IF F&&T&&F then F
...
IF F&&F&&F then F
So you need to re-evaluate what condition you want to cause to loop.
Are we looking for
(output==3 && Input=="shoot") || (output==1 && input=="reload") || (output==1 && input=="shoot")
to cause the next iteration?
This would make the case, where any of them are T, we get T. If all of them are F, then we get F.

Categories

Resources