I am trying to make a rock paper scissors game in java. i have my base code here
import java.util.Scanner;
import java.util.Random;
public class RPSBase
{
public static void main(String args[])
{
Random rndm = new Random();
int c =0 + rndm.nextInt(3);
Scanner c2 = new Scanner(System.in);
String pc = c2.next();
switch (c)
{
case 1:
String choice = "r";
char ch = choice.charAt(0);
break;
case 2:
choice = "p";
ch = choice.charAt(0);
break;
case 3:
choice = "s";
ch = choice.charAt(0);
break;
}
switch (ch)
{
case 'r':
if (pc == "r")
System.out.println("It's a tie");
else if (pc == "p")
System.out.println("win");
else if (pc == "s")
System.out.println("lose");
break;
case 'p':
if (pc == "p")
System.out.println("It's a tie");
else if (pc == "s")
System.out.println("win");
else if (pc == "r")
System.out.println("lose");
break;
case 's':
if (pc == "s")
System.out.println("It's a tie");
else if (pc == "r")
System.out.println("win");
else if (pc == "p")
System.out.println("lose");
break;
}
}
}
for some reason when i compile the program i get this error
1 error found:
File: C:\Users\Larry\RPSBase.java [line: 26]
Error: ch cannot be resolved to a variable
Why do i get this error and how do i fix it? I have tried switch(choice) as well and that didn't work either.
You either need to declare
ch
above theswitch (c)
, or declarech
in everycase
of the switch.And since you seem to be wanting to use
ch
at a later point, you need this snippet:Note the declaring (
char ch
) at the top, and in thecase
s there are just assignments.UPDATE: The same goes for
String choice
, however for this one it seems that it is better to declare it in everycase
.A lot of the code could be improved, but I'm just answering your question here, you can for example just type
ch = 'r'
instead ofString choice = "r"; ch = choice.charAt(0);