0

This is a tid bit of my total program, consisting of 4 classes. The classes goal is to print out a card with a numerical value and suit, the user than proceeds to guess wether the next card has a higher numerical value. If the cards are the same, the suit method determis the greatest suit in the order // SPADES >>>> HEARTS >>>> CLUBS >>>> DIAMONDS (As seen in the card method). The problem however, occurs in my HighLowrev class, in the do while loop as the user is asked to play again, if the user responds with 'y', the program continues and even if the user responds with 'n' the program continues. I have tried Looking up further usage of Boolean but have realized that I'm quite sure they work this way. Any help would be much appreciated.

CARD CLASS

public class Card {
  // card class initalize varibles (NOtice the FINAL (THEY NEVER CHANGE VALUE!!!))
  public final static int SPADES = 3;   // Codes for the 4 suits, plus Joker.
  public final static int HEARTS = 2;
  public final static int DIAMONDS = 0;
  public final static int CLUBS = 1;
  public final static int JOKER = 4;
  // SPADES >>>> HEARTS >>>> CLUBS >>>> DIAMONDS
  public final static int ACE = 1;      // Codes for the non-numeric cards.
  public final static int JACK = 11;    //   Cards 2 through 10 have their 
  public final static int QUEEN = 12;   //   numerical values for their codes.
  public final static int KING = 13;

  private final int suit; 

  private final int value;
  public static void main (String [] args){
  } // joker constructor
  public Card() {
    suit = JOKER;
    value = 1;
  }
  // incase an illegal field occurs
  public Card(int theValue, int theSuit) {
    if (theSuit != SPADES && theSuit != HEARTS && theSuit != DIAMONDS && 
        theSuit != CLUBS && theSuit != JOKER)
      throw new IllegalArgumentException("Illegal playing card suit");
    if (theSuit != JOKER && (theValue < 1 || theValue > 13))
      throw new IllegalArgumentException("Illegal playing card value");
    value = theValue;
    suit = theSuit;
  }

  public int getSuit() {
    return suit;
  }
  // getter methods
  public int getValue() {
    return value;
  }
  // cases for suits...
  public String getSuitAsString() {
    switch ( suit ) {
      case SPADES:   return "Spades";
      case HEARTS:   return "Hearts";
      case DIAMONDS: return "Diamonds";
      case CLUBS:    return "Clubs";
      default:       return "Joker";
    }
  }
  // cases for numerical values...
  public String getValueAsString() {
    if (suit == JOKER)
      return "" + value;
    else {
      switch ( value ) {
        case 1:   return "Ace";
        case 2:   return "2";
        case 3:   return "3";
        case 4:   return "4";
        case 5:   return "5";
        case 6:   return "6";
        case 7:   return "7";
        case 8:   return "8";
        case 9:   return "9";
        case 10:  return "10";
        case 11:  return "Jack";
        case 12:  return "Queen";
        default:  return "King";
      }
    }
  }   
  public String toString() {
    if (suit == JOKER) {
      if (value == 1)
        return "Joker"; // if the suit is the joker ....
      else
        return "Joker #" + value;
    }
    else { // return suit and number
        return getValueAsString() + " of " + getSuitAsString() ;
      }
    }

}

MAIN PROGRAM CLASS

import java.io.*;

public class HighLowrev {

  public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader (new InputStreamReader (System.in));  // allow input

    System.out.println("This program lets you play the simple card game,");
    System.out.println("HighLow.  A card is dealt from a deck of cards.");
    System.out.println("You have to predict whether the next card will be");
    System.out.println("higher or lower.  Your score in the game is the");
    System.out.println("number of correct predictions you make before");
    System.out.println("you guess wrong.");
    System.out.println();

    int gamesPlayed = 0;     // Number of games user has played.
    int sumOfScores = 0;     // The sum of all the scores from 
    //      all the games played.
    double averageScore;     // Average score, computed by dividing
    //      sumOfScores by gamesPlayed.
    boolean playAgain = true;;       // Record user's response when user is 
    //   asked whether he wants to play 
    //   another game.
    do {
         int scoreThisGame;        // Score for one game.
         scoreThisGame = play();   // Play the game and get the score.
         sumOfScores += scoreThisGame;
         gamesPlayed++;
         System.out.print("Play again? ");
         String input = br.readLine();
         if(input== "Y" || input =="y") {
           playAgain = true;
         }
         else {
          playAgain =false; 
         }
      } while (playAgain=true);

      averageScore = ((double)sumOfScores) / gamesPlayed;

      System.out.println();
      System.out.println("You played " + gamesPlayed + " games.");
      System.out.printf("Your average score was %1.3f.\n", averageScore);

   }  // end main()

  private static int play() throws IOException {
        BufferedReader br = new BufferedReader (new InputStreamReader (System.in));  // allow input
    Deck deck = new Deck();  // Get a new deck of cards, and 
    Card currentCard;  // The current card, which the user sees.
    Card nextCard;   // The next card in the deck.  The user tries
    int correctGuesses ;  // The number of correct predictions the
    char guess;   // The user's guess.  'H' if the user predicts that
    deck.shuffle();  // Shuffle the deck into a random order before
    correctGuesses = 0;
    currentCard = deck.dealCard();
    System.out.println("The first card is the " + currentCard);
    while (true) {  // Loop ends when user's prediction is wrong.

      /* Get the user's prediction, 'H' or 'L' (or 'h' or 'l'). */

      System.out.println("Will the next card be higher (H) or lower (L)?  ");
      do { /// THE SECTION HERE IS THE SPECIFIED PROBLEM, THE IF AND ELSE STATEMENTS DONT DO ANYTHING!
        guess = (char)br.read();
        guess = Character.toUpperCase(guess);
        if (guess != 'H' && guess != 'L') 
          System.out.println("Please respond with H or L:  ");
      } while (guess != 'H' && guess != 'L');

      nextCard = deck.dealCard();
      System.out.println("The next card is " + nextCard);

      if(nextCard.getValue() == currentCard.getValue()) {
        if(guess == 'H') {
        if(nextCard.getSuit() > currentCard.getSuit()) {
          System.out.println("Your prediction was correct.");
          correctGuesses++;
         }
        }
        else {
          System.out.println("Your prediction was incorrect.");
          break;  // End the game.
        }
        if(guess == 'L') {
        if(nextCard.getSuit() < currentCard.getSuit()) {
         System.out.println("Your prediction was correct.");
          correctGuesses++;
        }


        }
        else {
          System.out.println("Your prediction was incorrect.");
          break;

        }
     } 
      else if (nextCard.getValue() > currentCard.getValue()) {
        if (guess == 'H') {
          System.out.println("Your prediction was correct.");
          correctGuesses++;
        }
        else {
          System.out.println("Your prediction was incorrect.");
          break;  // End the game.
        }
      }
      else {  // nextCard is lower
        if (guess == 'L') {
          System.out.println("Your prediction was correct.");
          correctGuesses++;
        }
        else {
          System.out.println("Your prediction was incorrect.");
          break;  // End the game.
        }
      }
      currentCard = nextCard;
      System.out.println();
      System.out.println("The card is " + currentCard);

    } // end of while loop

    System.out.println();
    System.out.println("The game is over.");
    System.out.println("You made " + correctGuesses 
                         + " correct predictions.");
    System.out.println();    
    return correctGuesses;
  }  
} 

3 Answers3

4

String comparison in Java is not done with == but with String#equals

That is, instead of

if(input== "Y" || input =="y") {

You should be using something more like...

if("Y".equalsIgnoreCase(input)) {

Updated...

There is also a never ending assignment of true to playAgain

} while (playAgain=true); 

This will assign true back to playAgain, which means the loop can never be exited. Try using something like...

} while (playAgain); 

...instead

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • And even then, `while (playAgain=true)` will always be true, regardless of what the value of `playAgain` was before you assign `true` to it instead of comparison. – mustaccio Oct 17 '13 at 02:08
  • @mustaccio Yep, picked that up as well – MadProgrammer Oct 17 '13 at 02:09
  • This did indeed fix it, thanks for the input. Also I was wondering Why at times my Suit order is not taken into effect, as in Spades is not always greater than other suits when there is two of the same numerical values. Is it a fault in my program? – ClearCutFan Oct 17 '13 at 02:56
  • In your `if-else` statements, in the first one (where the value is equal), you compare the `suit`, but you do not for any of the others (where the card values are not equal) – MadProgrammer Oct 17 '13 at 02:59
  • Not exactlly sure what you mean, I have a line if they are greater if(nextCard.getSuit() > currentCard.getSuit()) { , and smaller. The part of which they are not equall is the else if statement below. – ClearCutFan Oct 17 '13 at 03:02
  • I "think" (half asleep), but your if statement would read something like...`if (3 > 2)` (`spades > hearts`), which is `true`, but `(2 > 3`) (`hearts > spades`) is false, so the order of the comparison matters – MadProgrammer Oct 17 '13 at 03:09
2

The variable you are comparing input is a String.

Strings cannot be equated using == you must use String#equals()

The == operator checks whether the references to the objects are equal. See this post

In this case you may want to use String#equalsIgnoreCase()

Also as mentioned you need to fix while (playAgain=true); This is assigning true the variable playAgain and will always be true, Here you want to use == or just the varaible itself (no need to compare booleans)

Community
  • 1
  • 1
Java Devil
  • 10,629
  • 7
  • 33
  • 48
0

while (playAgain=true);

should it be while (playAgain == true); ?

The comparison operator is not correct.

Kewell
  • 1