int levelP1;
int levelP2;
do {
p1.startTurn(p1, d1);
p2.startTurn(p2, d1);
levelP1 = p1.getLevel();
levelP2 = p2.getLevel();
} while (levelP1 <= 10 || levelP2 <= 10);
if (levelP1 >= 10) {
System.out.println(p1.getName() + " hit LvL " + levelP1 + " and WON the game !");
} else if (levelP2 >= 10) {
System.out.println(p2.getName() + " hit LvL " + levelP2 + " and WON the game !");
}
I have this pieace of code which is not doing what it is intended...
the "startTurn()" method might or might not level up the player, depending of what happens inside of it...
I want it to exit the loop when either player hits level 10 or above... Cannot figured out how. please help
I want it to exit the loop when either player hits level 10 or above.
Use && instead of || :
while (levelP1 < 10 && levelP2 < 10);
In this way, when one of these two conditions is false, you exit.
Related
I made a tic-tac-toe game using swing and a Jpanel. I got it to check for a winner. Now that I have a winner though, I don't want the user to be able to keep putting down more pieces in the game (even if there is room for pieces).
Here I have the last bit of code where _board represents the 3 x 3 board:
if (_board.testcrossDownwards() || _board.testcrossUpwards() || _board.testTopRow() || _board.testMiddleRow() || _board.testBottomRow() ||
_board.testLeftColumn() || _board.testMiddleColumn() || _board.testRightColumn()) {
_message.setText(player_name + " wins!");
} else if (_board.isTicTacRunThru()) {
_message.setText("It's a DRAW!");
} else {
_message.setText("You clicked on " + s.getCoordString() +". " + next_player_name + " to play.");
}
I assume that the piece that I need to add will follow the player_name + " wins!" line.
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
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Every time I increment the below to update the created by my method, I get a Exception in thread "main" java.lang.NullPointerException error. I have no clue what's causing this, perhaps it's the "do" loop? I've tried everything I can and am not aiming to import any packages
userCardsCount = 2;
boolean trueScore = userSum <= 21;
do{
displayCards(true);
// User turn
int i = 2;
System.out.println("\nUSER'S TURN");
System.out.print("Draw new card (Y/N): ");
input = br.readLine();
if(input.equals("y") || input.equals("Y") || input.equals("yes") || input.equals("YES")) {
userCardsCount++;
userCards[i] = deck.drawCard();
userSum += userCards[i].value;
System.out.print("\n--> User drew a " + "[" + userCards[i].value + "]\n");
//i++;
} else if(input.equals("n") || input.equals("N") || input.equals("no") || input.equals("NO")) {
// You stay as you are and go to the computer's turn
System.out.println("--> User stays.");
}
else {
System.out.println("\t--> Umm please retry input");
}
} while(trueScore);
METHOD
public static void displayCards(boolean showHidden)
{
if(showHidden) {
System.out.print("Computer's cards: [" + computerCards[0].name + "]");
} else {
System.out.print("Computer's cards: [X]");
}
for(int i = 1; i < computerCardsCount; i++) {
System.out.print("[" + computerCards[i].name + "]");
}
if(showHidden) {
System.out.print(" (sum: " + computerSum + ")");
}
System.out.print("\nUser's cards: ");
for(int i = 0; i < userCardsCount; i++) {
System.out.print("[" + userCards[i].name + "]");
}
System.out.print(" (sum: " + userSum + ")");
System.out.print("\n");
}
Any suggestions?
You should look at your array: computerCards. You seem to be entering that method with true always, so you will always call computerCards[0].name which might be empty. You should put a break point at the start of that method, and then debug to see if you have a value in the 0th position.
At the end of file br.readLine() will return null. And your next equals breaks.
I am trying to make a conditional statement with two "ifs", and it works when I input the correct thing, but when I input an incorrect pokemon and a correct level it still works. I am pretty sure that one of the conditions in my while statement is always true (the first part). Here is the code (sorry about the formatting, just know that it is all formatted correctly in the Java environment):
while ((!(Pokemon.equalsIgnoreCase(Pikachu)) || !(Pokemon.equalsIgnoreCase(Charmander)) || !(Pokemon.equalsIgnoreCase(Squirtle)) || !(Pokemon.equalsIgnoreCase(Bulbasaur))) && !((Level <= 15)&&(Level >= 1 ))) {
System.out.println();
System.out.println("Which one would you like? What level should it be?\n1 to 15 would be best, I think.");
Pokemon = sc.next();
Level = sc.nextInt();
if ((Level <= 15) && (Level >= 1)) {
if ((Pokemon.equalsIgnoreCase(Pikachu)) || (Pokemon.equalsIgnoreCase(Charmander)) || (Pokemon.equalsIgnoreCase(Squirtle)) || (Pokemon.equalsIgnoreCase(Bulbasaur))) {
System.out.print("Added level " + Level + " " + Pokemon + " for " + Trainer + ".");
}
else {
System.out.println("Invalid Pokemon!");
}
}
else {
System.out.println("Invalid Level!");
}
}
Pokeman will always be either not X or not Y, it's basic logic since if it's X, then not-Y is true. If it's Y, then not-X is true. If it's neither then both will be true.
Change || to && and think through your logic on paper.
Should be:
while ((!(Pokemon.equalsIgnoreCase(Pikachu)) &&
!(Pokemon.equalsIgnoreCase(Charmander)) &&
!(Pokemon.equalsIgnoreCase(Squirtle)) &&
!(Pokemon.equalsIgnoreCase(Bulbasaur))) &&
!((Level <= 15)&&(Level >= 1 )))
I'm working on a program to play the game of Go Fish. Everything works except for the scan.next() after looping through once.
Well, sometimes it works and sometimes it doesn't. Here's the code:
System.out.println(compHand.showHand());
while (!(deck.isEmpty())) {
y = 0;
while (x == 1) {
System.out.println("\nYour hand:" + userHand.showHand()+ "\nYour turn. What number do you want to match?");
guess = scan.next();
if (compHand.checkHand(guess)) {
System.out.println("Darn...here you go.");
userHand.removeNum(guess);
compHand.removeNum(guess);
userHand.showHand();
uP++;
}
else {
System.out.println("Nope! Type '1' to go fish!");
y = scan.nextInt();
if (y == 1) {
userHand.goFish();
System.out.println(userHand.showHand());
}
y = 0;
}
guess = "";
x--;
}
while (x == 0) {
System.out.println("Do you have any " + compHand.ask() + "s?");
ans = scan.next();
if (!(ans.contains("go"))) {
System.out.println("Yay!");
userHand.removeNum(ans);
compHand.removeNum(ans);
cP++;
x++;
}
else {
System.out.println("Aww...darn.");
compHand.goFish();
x++;
}
}
System.out.println("Computer's points so far: " + cP + "\nYour points so far: " + uP + "\n");
}
}
So the first time it loops through to do the user's hand, it works. Then it works for the computer's turn, but if the computer has to go fish. When it loops back up to the user's hand it skips the guess = scan.next();.
I don't know what to do...
The problems comes from the buffer. You have to free it. To do so, put a scan.nextLine() just before the closing bracket of the loop and it will free the buffer. You will be able then to enter an input.