I'm having a few issues. I'm trying to write a simple rock paper scissors game and I put the main function in a do while loop. At the beginning I ask for the string user input, then generate the random number for the programs move, then run through if statements to determine the winner and at the end I ask if the player would like to play again. The first issue is that no matter what input it tells me it's a loss. The second is that when I go through the loop the second time it skips the user input and just gives you the loss message without you making a move.
Here's the code:
import java.util.Scanner;
import java.util.Random;
public class RPS
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random rand = new Random();
char PA;
do
{
String RGW;
System.out.println("Rock Paper or Scissors?");
String PI = input.nextLine();
int RGrand.nextInt(3);
if(RG == 0)
{
RGW = "Rock";
}
else if(RG == 1)
{
RGW = "Paper";
}
else
{
RGW = "Scissors";
}
System.out.println("Opponents Move: " + RGW + "\nYour Move: " + PI);
if(PI == RGW)
{
System.out.println("It's a Tie!");
}
else if((PI == "Rock" && RGW == "Scissors") || (PI == "Scissors" && RGW == "Paper") || (PI == "Paper" && RGW == "Rock"))
{
System.out.println("You Win!");
}
else
{
System.out.println("You Lose!");
}
System.out.println("Play Again? Y/N");
PA = input.next().charAt(0);
}
while(PA == 89 || PA == 121);
}
}
For the loss message I've tried writing out each combination of win, loss, and tie conditions and I've tried saying if userInput = oppInput it's a tie. It still just tells me it's a loss.
For the skipping input issue I've tried putting the generation after the input statement and I've tried putting it in an if statement that only runs if the user input is not empty. it still skips and goes straight to the loss message.
First thing that the String PI = input.nextLine(); Skips in 2nd loop because the Scanner class is nextLine() sometimes skips taking the input
So try next() Only to take input
i have fixed the code and Here is the fixed code
in this code try to handle the user input so the code does not break or shows the different output for invalid input
use the Input validation for this and your code should be ready for some game play
don't compare the strings directly in java because the java compares the memory address of the string for the two strings which are not same so you always gets the false for that comparision .