I am trying to get the "press q to quit" function to work properly, but I'm having some trouble. The "invalid Character" function is also not working properly. How would I go about fixing this? My professor suggested putting the "press q to quit" function in the beginning of my code, but hasn't given me any further instruction.
public static void main(String[] args) {
char userChar = 0;
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
// Intro/directions/prompting for user input
System.out.println("Welcome to Rock, Paper, Scissors by Rancid!");
System.out.println("Choose R for Rock, P for Paper, S for Scissors, or Q to Quit, then press Enter: ");
// If player chooses to quit
if (userChar == 'q' || userChar == 'Q') {
System.out.println("Player chose to quit. Goodbye!");
}
// Start of loop
while (userChar != 'q' && userChar != 'Q') {
// Prompting computer to generate a random number
int randomNumber = rnd.nextInt(3) + 1;
// If computer generates 1 (Rock)
if (randomNumber == 1) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Rock vs. Rock! It's a tie!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Paper covers Rock, you win!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Rock breaks Scissors, you lose!");
}
}
// If computer generates 2 (Paper)
else if (randomNumber == 2) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Paper covers Rock, you lose!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Paper vs. Paper! It's a tie!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Scissors cuts Paper, you win!");
}
}
// If computer generates 3 (Scissors)
else if (randomNumber == 3) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Rock breaks Scissors, you win!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Scissors cuts Paper, you lose!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Scissors vs. Scissors! It's a tie!");
}
}
// If player types an invalid character
else {
System.out.println("Invalid input! Please enter a valid character.");
}
userChar = sc.next().charAt(0);
}
}
}
In order to really take care of invalid input you need to do it first thing in the loop. Moreover you can't do it in the else block of your if-else statements because in those if-else you check the randomNumber, not the input, so it doesn't make sense and it will never work. In addition you check the input as what you get from sc.next().charAt(0) but for example if the user insert a string like "R_invalid_something_without_space" you only look at the first letter which is R and you take it as a valid input. I modified your code so that you read a line in each loop iteration and if this line is not q / r / p / s it will consider as invalid input and if its q the program will finish.
public static void main(String[] args) {
char userChar = 0;
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
// Intro/directions/prompting for user input
System.out.println("Welcome to Rock, Paper, Scissors by Rancid!");
System.out.println("Choose R for Rock, P for Paper, S for Scissors, or Q to Quit, then press Enter: ");
// Start of loop
while (true) {
// what I changed
// **********************************************************
String line = sc.nextLine().toLowerCase();
if(line.equals("q")){
System.out.println("Player chose to quit. Goodbye!");
break;
}
if(!line.equals("r") && !line.equals("s") && !line.equals("p")) {
System.out.println("Invalid input! Please enter a valid character.");
continue;
}
userChar = line.charAt(0);
// **********************************************************
// Prompting computer to generate a random number
int randomNumber = rnd.nextInt(3) + 1;
// If computer generates 1 (Rock)
if (randomNumber == 1) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Rock vs. Rock! It's a tie!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Paper covers Rock, you win!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Rock breaks Scissors, you lose!");
}
}
// If computer generates 2 (Paper)
else if (randomNumber == 2) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Paper covers Rock, you lose!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Paper vs. Paper! It's a tie!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Scissors cuts Paper, you win!");
}
}
// If computer generates 3 (Scissors)
else if (randomNumber == 3) {
if (userChar == 'r' || userChar == 'R') {
System.out.println("Rock breaks Scissors, you win!");
} else if (userChar == 'p' || userChar == 'P') {
System.out.println("Scissors cuts Paper, you lose!");
} else if (userChar == 's' || userChar == 'S') {
System.out.println("Scissors vs. Scissors! It's a tie!");
}
}
}
}
Well, firstly your condition to quit is outside of scope of while loop which means it will never execute in this given context.
Secondly, condition in your while loop will not be true unless userChar is not q and Q simultaneously, which doesn't make sense.
What I suggest is to refactor your while loop little bit, as such:
while (true) {
//Your logic here
if (userChar == 'q' || userChar == 'Q') {
System.out.println("Player chose to quit. Goodbye!");
break;
}
//Your logic here
}
Related
I'm new to programming and have been attempting to code a simple Rock Paper Scissors game in Java, but I'm stuck with two problems. The game worked correctly prior to me adding a for loop in order to make the game last for 5 rounds each time, but now with the loop it just repeats the same result line 4 times after entering 1 input, rather than allowing me to enter more inputs and generate several results. I also tried putting in an invalid input message, where if the user inputs anything other than 1, 2 or 3 the program outputs "Invalid user input.", but this doesn't work when ran and has just resulted in compiler error messages.
Any help would be greatly appreciated, thanks!
Here is the entirety of my code:
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static final int ROCK = 1;
public static final int PAPER = 2;
public static final int SCISSORS =3;
public static void main(String[] args) {
System.out.println("Let's play Rock, Paper, Scissors! (best out of 5)");
System.out.println("Enter either 1 for Rock, 2 for Paper or 3 for Scissors.");
Scanner input = new Scanner(System.in);
int numberGuessed = input.nextInt();
Random generator = new Random();
int computerNumber = generator.nextInt(3) + 1;
for (int round = 0; round < 4; round++) {
if (numberGuessed == computerNumber) {
System.out.print("It's a tie!");
}
if (numberGuessed == 1 && computerNumber == 2) {
System.out.println("You lose! I chose paper and paper smothers rock!");
}
else if (numberGuessed == 1 && computerNumber == 3) {
System.out.println("You win! I chose scissors and rock smashes scissors!");
}
else if (numberGuessed == 2 && computerNumber == 1) {
System.out.println("You win! I chose rock and paper smothers rock!");
}
else if (numberGuessed == 2 && computerNumber == 3) {
System.out.println("You lose! I chose scissors and scissors cut paper!");
}
else if (numberGuessed == 3 && computerNumber == 2) {
System.out.println("You win! I chose paper and scissors cut paper!");
}
else if (numberGuessed == 3 && computerNumber == 1) {
System.out.println("You lose! I chose rock and rock smashes scissors!");
}
else if (numberGuessed != 1 || numberGuessed != 2 || numberGuessed != 3) {
System.out.println("Invalid user input.");
}
}
You have not ended all of the curly braces properly which is leading to compiler error.
for (int round = 0; round < 4; round++) will end for upto 4 rounds, for 5 rounds of loop the condition can be like this: for (int round = 0; round < 5; round++)
The for loop should start before the input is taken each time so that it can process each input separately.
Try this:
import java.util.Random;
import java.util.Scanner;
class RockPaperScissors {
public static final int ROCK = 1;
public static final int PAPER = 2;
public static final int SCISSORS = 3;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Let's play Rock, Paper, Scissors! (best out of 5)");
for (int round = 0; round < 5; round++) {
System.out.println("Enter either 1 for Rock, 2 for Paper or 3 for Scissors.");
int numberGuessed = input.nextInt();
Random generator = new Random();
int computerNumber = generator.nextInt(3) + 1;
if (numberGuessed == computerNumber) {
System.out.println("It's a tie!");
} else if (numberGuessed == 1 && computerNumber == 2) {
System.out.println("You lose! I chose paper and paper smothers rock!");
} else if (numberGuessed == 1 && computerNumber == 3) {
System.out.println("You win! I chose scissors and rock smashes scissors!");
} else if (numberGuessed == 2 && computerNumber == 1) {
System.out.println("You win! I chose rock and paper smothers rock!");
} else if (numberGuessed == 2 && computerNumber == 3) {
System.out.println("You lose! I chose scissors and scissors cut paper!");
} else if (numberGuessed == 3 && computerNumber == 2) {
System.out.println("You win! I chose paper and scissors cut paper!");
} else if (numberGuessed == 3 && computerNumber == 1) {
System.out.println("You lose! I chose rock and rock smashes scissors!");
} else if (numberGuessed != 1 || numberGuessed != 2 || numberGuessed != 3) {
System.out.println("Invalid user input.");
}
System.out.println();
}
}
}
You set numbers and do 5 rounds on the same data. Move initialization of numberGuessed and computerNumber inside for loop.
Observe where your input and random number generator is. Think if that will repeat 5 times when your loop runs. Done?
If you haven't observed yet, let me elaborate: your input and random number generator is outside you for loop. That's IT.
I've written out all the code for an assignment for my programming class. The assignment requires us to create a program that allows the user to play rock paper scissors against a computer. We're required to have individual methods to obtain the computer's choice, the user's choice, check if the user's choice is valid, and also to determine the winner of the match. If a match doesn't end in a tie we need to print why the match was won, eg. "Scissors cuts Paper," and print who wins. Everything works properly, except when the user wins it's never counted or announced. For example instead of printing:
The computer's choice was rock. The user's choice was paper. Paper covers Rock. The user wins!
it prints:
The computer's choice was rock. The user's choice was paper. Paper covers Rock.
import java.util.Scanner;
import java.util.Random;
public class FinalRockPaperScissors {
//Computer's Choice
public static int computersChoice (int options) {
Random randGen = new Random();
int computerValue = randGen.nextInt(options)+1;
System.out.println(computerValue); //FOR TESTING ONLY
return computerValue;
}
//Player's Choice
public static int usersChoice () {
Scanner scnr = new Scanner(System.in);
System.out.print("Enter 1 for rock, 2 for paper, or 3 for scissors: ");
int userValue = scnr.nextInt();
if (isValid(userValue) == true) {
return userValue;
}
else {
userValue = 0;
return userValue;
}
}
//Check for valid user input
public static boolean isValid (int userInput){
if (userInput == 1 || userInput == 2 || userInput == 3) {
return true;
}
else {
return false;
}
}
//Checking winner
public static char determineWinner () {
char win;
int computerValue = computersChoice(3);
int userValue = usersChoice();
//print computer choices
if (computerValue == 1) {
System.out.println("The computer's choice was rock.");
}
else if (computerValue == 2) {
System.out.println("The computer's choice was paper.");
}
else if (computerValue == 3){
System.out.println("The computer's choice was scissors.");
}
//print user choices
if (userValue == 1) {
System.out.println("The user's choice was rock.");
}
else if (userValue == 2) {
System.out.println("The user's choice was paper.");
}
else if (userValue == 3){
System.out.println("The user's choice was scissors.");
}
//check who won
if (computerValue == 1) { //rock vs
if (userValue == 2) { //paper
System.out.println("Paper wraps Rock.");
return win = 'b';
}
else if (userValue == 3) { //scissors
System.out.println("Rock smashes Scissors.");
return win = 'a';
}
else if (userValue == 1){ //rock
return win = 'c';
}
else {
System.out.println("The user chose an invalid number. This round will be ignored.");
return win = 'd';
}
}
else if (computerValue == 2) { //paper vs
if (userValue == 2) { //paper
return win = 'c';
}
else if (userValue == 3) { //scissors
System.out.println("Scissors cuts Paper.");
return win = 'b';
}
else if (userValue == 1){ //rock
System.out.println("Paper wraps Rock.");
return win = 'a';
}
else {
System.out.println("The user chose an invalid number. This round will be ignored.");
return win = 'd';
}
}
else { //scissors vs
if (userValue == 2) { //paper
System.out.println("Scissors cuts Paper.");
return win = 'a';
}
else if (userValue == 3) { //scissors
return win = 'c';
}
else if (userValue == 1){ //rock
System.out.println("Rock smashes Scissors.");
return win = 'b';
}
else {
System.out.println("The user chose an invalid number. This round will be ignored.");
return win = 'd';
}
}
}
public static void main(String[] args) {
int userWins = 0;
int computerWins = 0;
int ties = 0;
int error = 0;
//for (int i = 0; i < 1; i++) { //5 for testing purposes
if (determineWinner() == 'a') {
System.out.println("The computer wins!");
System.out.println("");
computerWins++;
}
else if (determineWinner() == 'b') {
System.out.println("The user wins!");
System.out.println("");
userWins++;
}
else if (determineWinner() == 'c'){
System.out.println("The game is tied!");
System.out.println("");
ties++;
}
else {
error++;
}
//}
System.out.println("The number of ties is " + ties);
System.out.println("The number of user wins is " + userWins);
System.out.println("The number of computer wins is " + computerWins);
//output final winner
if (computerWins > userWins) {
System.out.println("Computer is the winner.");
}
else if (userWins > computerWins) {
System.out.println("User is the winner.");
}
else {
if (userWins == computerWins) {
System.out.println("User is the winner.");
}
else if (computerWins == ties) {
System.out.println("Computer is the winner.");
}
}
}
}
After some testing I've discovered that the problem may be with my userchoice() method. If I disable this method and give a set value for the user, everything works as it should. The problem is I don't know why it doesn't work, and as a result I can't fix it.
I think you're so new to Java and also let's start to show you your mistake in this code, you called determineWinner() multiple times which shouldn't be like that because you repeat the game four times to determine the result once, so you should call it once and get the returned value and check the value, like:-
char result = determineWinner(); //Play the game and get the result
// use it in conditions
if (result == 'a') {
System.out.println("The computer wins!");
System.out.println("");
computerWins++;
}
else if (result == 'b') {
System.out.println("The user wins!");
System.out.println("");
userWins++;
}
else if (result == 'c'){
System.out.println("The game is tied!");
System.out.println("");
ties++;
}
else {
error++;
}
In your main function You are calling determineWinner() every time you test your if condition. The proper way would be to store the returned value in a variable and then check if that variable is 'a', 'b' or 'c'. For example:
char result = determineWinner();
if (result == 'a') {
System.out.println("The computer wins!");
System.out.println("");
computerWins++;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
So I'm creating a simple rock paper scissors and I have made a mistake recently. I'm just beginning to learn and I made a mistake and lost track of where. I'd really really appreciate any pointers of where I made a mistake. When it prints out the prompt, I type in what I want, and it just prints it out again. Thank you!
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class rock_Paper_Scissor {
public static void main (String[] args) {
String playerhand;
boolean x = true;
Scanner input = new Scanner(System.in);
Random num = new Random();
int rand = num.nextInt(2) + 1;
System.out.println("I challenge you to Rock Paper Scissor");
System.out.println("If you want to quit, type exit twice");
System.out.println("Type Rock, Paper, or scissor");
playerhand = input.nextLine();
String hands = playerhand.toLowerCase();
while (x == true) {
if (hands == "rock") {
if (rand == 1) {
System.out.println("Rock vs. Rock: TIE");
} else if (rand == 2) {
System.out.println("Rock vs. Scissor: YOU WIN");
} else if (rand == 3) {
System.out.println("Rock vs. Paper: YOU LOSE");
}
}
else if (hands == "paper") {
if (rand == 1) {
System.out.println("Paper vs. Rock: YOU WIN");
} else if (rand == 2) {
System.out.println("Paper vs. Scissor: YOU LOSE");
} else if (rand == 3) {
System.out.println("Paper vs. Paper: TIE");
}
}
else if (hands == "scissor") {
if (rand == 1) {
System.out.println("Scissor vs. Rock: YOU LOSE");
} else if (rand == 2) {
System.out.println("Scissor vs. Scissor: TIE");
} else if (rand == 3) {
System.out.println("Scissor vs. Paper: YOU WIN");
}
}
else if (hands == "exit") {
System.out.println("Thank you for playing!");
x = false;
}
System.out.println("Please type your hand to play again: ");
hands = input.nextLine();
}
}
}
In your all if condition try to use eqauls() method instead of == like this:
if ("rock".equals(hands)) {
...
else if ("paper".equals(hands)) {
...
else if ("scissor".equals(hands )) {
...
else if ("exit".equals(hands)) {
.equals() is used to compare strings values.
But == compare with references strings.
When I run this, it displays all System.out.println("") statements in the case. How do I make it choose the correct if statement and nothing else?
And if I could go back to the beginning after it finds an outcome, that would also be helpful.
import java.util.Scanner;
import java.util.Random;
public class TEST {
private static Scanner myScanner;
public static void main(String[] args) {
myScanner = new Scanner(System.in);
Random myRandom = new Random();
int randomNumber;
char reply;
System.out.print("Rock(R) Paper(P) or Scissors(S)? ");
reply = myScanner.findWithinHorizon(".", 0).charAt(0);
randomNumber = myRandom.nextInt(3) + 1;
switch (randomNumber) {
case 1:
if (reply == 'S' || reply == 's'); {
System.out.println("Computer: Rock. You lost!");
}
if (reply == 'R' || reply == 'r'); {
System.out.println("Computer: Rock. You tied!");
}
if (reply == 'P' || reply == 'p'); {
System.out.println("Computer: Rock. You won!");
break;
}
case 2:
if (reply == 'P' || reply == 'p'); {
System.out.println("Computer: Paper. You tied!");
}
if (reply == 'S' || reply == 's'); {
System.out.println("Computer: Paper. You won!");
}
if (reply == 'R' || reply == 'r'); {
System.out.println("Computer: Paper. You lost!");
break;
}
case 3:
if (reply == 'R' || reply == 'r'); {
System.out.println("Computer: Scissor. You won!");
}
if (reply == 'P' || reply == 'p'); {
System.out.println("Computer: Scissor. You lost!");
}
if (reply == 'S' || reply == 's'); {
System.out.println("Computer: Scissor. You tied!");
break;
}
}
}
}
You have two problems:
1) Your if statements don't run because they end in semi-colon. This means the code in {} forms a block and runs either way.
2) Your breaks are in the wrong place. The first only breaks if 'R' (or 'r') is chosen. The later breaks if the case is run.
if (reply == 'P' || reply == 'p'); {
System.out.println("Computer: Paper. You tied!");
}
if (reply == 'S' || reply == 's'); {
System.out.println("Computer: Paper. You won!");
}
if (reply == 'R' || reply == 'r'); {
System.out.println("Computer: Paper. You lost!");
break;
}
vs
if (reply == 'P' || reply == 'p') {
System.out.println("Computer: Paper. You tied!");
}
if (reply == 'S' || reply == 's') {
System.out.println("Computer: Paper. You won!");
}
if (reply == 'R' || reply == 'r') {
System.out.println("Computer: Paper. You lost!");
}
break;
Also, as suggested in the comments, you can use a loop to prompt for input. For example:
while (! done) {
System.out.print("Rock(R) Paper(P) or Scissors(S)? (or Quit(Q) ");
reply = myScanner.findWithinHorizon(".", 0).charAt(0);
// more code here
}
You'll need another case here so you can set done to true and end the loop.
You followed the if's with an extra ;
The syntax for an if statements is:
if(condition){
Expressions;
}
the semicolon makes it:
if(condition)
; //empty line, effectively ignores the if
{
Expressions;
}
I'm having to make a paper rock scissors program that has the user enter in a choice, then tests it against the computer's choice. After every game, it should ask the player if they want to continue, and they should enter in 'Y' or 'N' to continue or quit. The best I could think was a while loop, and everything works fine except the very last bit.
import java.util.Scanner;
public class rockpaperscissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char cont = 'y';
while (cont == 'y'){
int com = (int)(Math.random() * 3);
System.out.println("Paper (0), Rock (1), or Scizzors (2)?");
int hum = input.nextInt();
if (com==(hum))
System.out.println("It's a tie!");
else if (hum == 0)
{
if (com == 1)
System.out.println ("You chose paper, computer chose rock You Win!");
else if (com == 2)
System.out.println ("You chose paper, Computer chose scissors You Lose!");
}
else if (hum == 1)
{
if (com == 2)
System.out.println ("You chose Rock, computer chose scissors You Win!");
else if (com == 0)
System.out.println ("You chose Rock, Computer chose paper You Lose!");
}
else if (hum == 2)
{
if (com == 0)
System.out.println ("You chose Scissors, computer chose paper You Win!");
else if (com == 1)
System.out.println ("You chose Scissors, Computer chose rock You Lose!");
}
System.out.println("Would you like to continue? (Y/N)");
cont = input.nextLine().charAt(0);
}
}
}
When I run it, the loop runs fine, the game is played, but then I get a 'string out of index range' error. Any idea how to resolve this?
Your nextInt() just reads the number from the input buffer, leaving the new line in it. So when you call input.nextLine() you're getting an empty line - the rest of the first line after the number. You should read the next-line and make sure it's not empty. If it is, just read it again.
Incidentally, your code that figures out who won is a bit cumbersome. If I were you, I would try to make it a little more general and clean. Think about a solution that can handle a more complex game, such as Rock Paper Scissors Lizard Spock without adding too much code.
When you get the answer from the user, you don't read the next line so the scanner still has a new line character. Then when you read the nextline you read that new line, and therefore there is no charat(0).
Change:
cont = input.nextLine().charAt(0);
to:
cont = input.next().charAt(0);
package rockpaper;
import java.util.Scanner;
/**
*
* #author Allen E.
*/
public class RockPaper {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int rock = 0;
int paper = 1;
int Scissors = 2;
int user = 0;
int computer = 0;
int gamesplayed = 0;
Scanner scan = new Scanner(System.in);
while (gamesplayed < 3)
{
System.out.println("Rock = 0 , Paper = 1, Scissors = 2");
String userinput = scan.nextLine();
int convertinput = Integer.valueOf(userinput);
int Computerinput = (int)(Math.random()*3);
if (Computerinput == 1 && convertinput == 0)
{
System.out.println("Paper beats Rock " +
"\nThe computer won");
gamesplayed++;
computer++;
}
else if (convertinput == 1 && Computerinput == 0)
{
System.out.println("Paper beats Rock " +
"\nYou Win!");
gamesplayed++;
user++;
}
if (Computerinput == 0 && convertinput == 2)
{
System.out.println("Rock beats Scissors " +
"\nThe computer won");
gamesplayed++;
computer++;
}
else if (convertinput == 0 && Computerinput == 2)
{
System.out.println("Rock beats Scissors " +
"\nYou Win!");
gamesplayed++;
user++;
}
if (Computerinput == 2 && convertinput == 1)
{
System.out.println("Scissors beats Paper " +
"\nThe computer won");
gamesplayed++;
computer++;
}
else if (convertinput == 2 && Computerinput == 1 )
{
System.out.println("Scissors beats Paper " +
"\nYou Win");
gamesplayed++;
user++;
}
/*************************************************
* *
* *
* Handling a tie *
* *
* *
*************************************************/
if (Computerinput == 0 && convertinput == 0)
{
System.out.println("Rock ties Rock " +
"\nTie");
}
if (Computerinput == 1 && convertinput == 1)
{
System.out.println("Paper ties Paper " +
"\nTie");
}
if (Computerinput == 2 && convertinput == 2)
{
System.out.println("Scissors ties Scissors " +
"\nTie");
}/*End of While Loop*/
}
}
}