"Not equals" can be expressed with the "not" operator ! and the standard .equals.
if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b
Answer from Anthony Pegram on Stack OverflowVideos
I’m writing code for a rock, paper, scissors game and I need to check the users input to make sure they input Rock, Paper, or Scissors. I know that you can use “!=“ to compare two strings and “.equals” in an if-else statement. For the most part I have the entries, as well as the comparing the two entries to see who wins, however, I’m having trouble checking to make sure their input is correct to proceed on, I’ve tried “!=“ but it automatically will default to “Wrong Choice!” (as I have that as what will output if their entry isn’t either of the options) and I can’t seem to figure it out. Any ideas on how I would do that?
Here is the code I have for it so far,
import java.util.Scanner;
public class Assignment2 { public static void main (String[]args) { String player1; String player2;
Scanner keyboard = new Scanner(System.in);
System.out.println("*****Hello! Welcome to the Rock, Paper, Scissors Program*****");
System.out.println("Rules: This is a two player game, both players must take turns entering their choice");
System.out.println("\tRemember, rock beats scissors, scissors beats paper, and paper beats rock!");
System.out.println("Player 1: Choose rock, paper, or scissors: ");
player1= keyboard.nextLine();
if ((player1 != "Rock") || (player1 != "Paper") || (player1 != "Scissors" ))
{
System.out.println("Wrong Choice!");
player1 = keyboard.nextLine();
}
else
{
player2 = keyboard.nextLine();
}
System.out.println("Player 2: Choose rock, paper, or scissors: ");
player2=keyboard.nextLine();
if (player1.equalsIgnoreCase("Rock") && player2.equalsIgnoreCase("Scissors"))
{
System.out.println("Player 1 wins!");
}
else if (player1.equalsIgnoreCase("Scissors")&&player2.equalsIgnoreCase("Paper"))
{
System.out.println("Player 1 wins!");
}
else if (player1.equalsIgnoreCase("Paper")&&player2.equalsIgnoreCase("Rock"))
{
System.out.println("Player 1 wins!");
}
else if (player1.equalsIgnoreCase(player2))
{
System.out.println("It's a tie!");
}
else
{
System.out.println("Player 2 wins!");
}
keyboard.close();
}}