0

I'm writing a program that keeps track of team names and how many times that team has won a game based on user input. I need to allow for the user to input a String (for the team name) and an x to exit. I need to be able to compare a string and a character in a while loop (while (String != x)). So far I've tried:

char exitProgram = 'x';
String x = Character.toString(exitProgram);
while (winningTeam != x)

as well as:

while (winningTeam.charAt(0) != 'x')

However, neither of these result in a while loop that exits when x is entered. I'm not sure if it's a problem with trying to turn a char into a String or if I'm doing something else wrong but I'm pretty sure it's something I'm not understanding with the comparison. Any help is appreciated.

Edit: This has been marked as a duplicate of How do I compare strings in Java?

and while they're similar, I believe my question differs in needing to know how to compare a character to a string (i.e finding the correct character to string conversion) rather than just comparing two strings.

  • Since `String` is an Object, it's best to use the included `equals()` method. eg `myString.equals("test")` – Richard Jul 09 '18 at 20:39
  • 1
    Please see [How do I compare strings in Java?](https://stackoverflow.com/q/513832/1553851) and provide a [mcve]. – shmosel Jul 09 '18 at 20:39
  • Why is exitProgram a Char? Does it have to be or can it be a string? – Rob Jul 09 '18 at 20:42
  • Your 2nd comparison is fine. You need to provide more code. Please read about creating a [mcve]. – 001 Jul 09 '18 at 21:06
  • Eclipse recognizes 'x' as a char, I tried to cast exitProgram as a string and the program wouldn't compile. Thank you for the idea, though. As for using .equals(), I'm continuing to have the same problem. Luckily I can talk to my TA tonight during office hours. Thanks you guys for the recommendations! – Reagan Shirk Jul 09 '18 at 21:11
  • With your first example, you can use `while (!x.equals(winningTeam)) {...}` (per *How do I compare strings in Java?*). – Radiodef Jul 09 '18 at 23:04

0 Answers0