In: Computer Science
Write a Java class that determines the winner of a rock, paper scissors game. Assume the input from the user is always valid (so no need to check), that is it contains either one of `R`, `P`, or `S` as a single character, or has matching parenthesis, like, `(S&P)` or `((R&P)&S)`, and the `&` character.
So for example, the user inputs `(P&R)` and the program will output `P` since paper beats rock. Or if the user inputs `((S&R)&(S&S))` the output is `R` because rock beats scissors, S&S is S, and R&S -> R
One more example is if the user inputs: `(((R&P)&(P&S))&R)` the output is `R` because (((R&P)&(P&S))&R --> (((P)&(S))&R --> (S)&R --> R
Hello There,Thanks for Asking to Answer.Here we can see that we have to use the Java Regex for pattern matching as well as for checking the input. In this answer i am providing you the basic format of the above question.
Code:-
import java.util.*;
import java.io.*;
import java.util.regex.*;
class myclass{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the First
Input:-");
String a = sc.nextLine();
String aa = new String(a.toLowerCase());
System.out.println("Enter the Second
Input:-");
String b = sc.nextLine();
String bb = new String(b.toLowerCase());
if(aa.matches("(.*)rock(.*)") &&
bb.matches("(.*)scissors(.*)") || bb.matches("(.*)rock(.*)")
&& aa.matches("(.*)scissors(.*)")){
System.out.println("The output is R
because Rock beats Scissors");
}else if(aa.matches("(.*)paper(.*)") &&
bb.matches("(.*)rock(.*)") || bb.matches("(.*)paper(.*)")
&& aa.matches("(.*)rock(.*)")){
System.out.println("The output is
Paper because Rock beats Rock");
}if(aa.matches("(.*)scissors(.*)") &&
bb.matches("(.*)paper(.*)") || bb.matches("(.*)scissors(.*)")
&& aa.matches("(.*)paper(.*)")){
System.out.println("The output is S
because Scissors beats Paper");
}else if(a.equals(b)){
System.out.println("both inputs are
same");
}
}
}
I Hope it fufiled Your Requirements.However,if you need that this answer need some modification or there is any error in the code then do let me know in the Comments.
Happy Learning!!!.