0

What am I doing wrong? I need the game to repeat until a user enters N or n. Instead, it just keeps going and going and going......

import java.util.Scanner;

public class Test {

   public static void main(String[] args) {

       int noOfPlayers;
       String playAgain;

       Scanner game = new Scanner(System.in);

       do {
       System.out.print("How many players in the game :");
       noOfPlayers = game.nextInt();
       if(noOfPlayers > 5) {
           System.out.println("Only 5 or less players can play.");
           System.out.println("How many players in the game (1-5) :");
           noOfPlayers = game.nextInt();
       }


       Game g=new Game(noOfPlayers);
       g.readPlayernames();
      
       g.playGame();
       
       System.out.println("Would you like to play again? Y or N.");
       playAgain = game.next();      
              
    }
       while(playAgain != "Y" || playAgain !="y");
   }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

-1

Strings cannot be compared with the == and != operators, they use the .equals. There is also a .equalsIgnore case that will help in your situation. For the while comparison, try while(playAgain.equalsIgnoreCase("n"))

rakers
  • 41
  • 6
  • Thanks for the help! I think I got it! – ChaoticDreamer Mar 05 '21 at 19:18
  • 2
    Please don't answer questions that are clearly duplicates. A link with an answer has already been given, no need to add another one. – Federico klez Culloca Mar 05 '21 at 19:18
  • @FedericoklezCulloca ChaocticDreamer is clearly a new programmer and your link did not help him. He did not figure out his issue until I answered, so that should get my answer voted up based on how stack defines the voting. – rakers Mar 05 '21 at 19:31
  • @rakers the post is closed by the Community user, which means ChaoticDreamer accepted the link as a duplicate to their question. – Federico klez Culloca Mar 05 '21 at 19:33
  • @FedericoklezCulloca he obviously closed it after I answered or I would not have been able to even provide an answer. Also he commented under my answer saying I helped him and did not respond to you. – rakers Mar 05 '21 at 19:37