I'm currently working on an assignment for my Intro to Java Course. I've completed majority of the assignment: refactor a Rock, Paper, Scissor game I created in the past but using methods. When my code is executed; it prints a welcome message, prompts for user input and then prints the user's choice and the CPU's choice.
My question: How do i implement a while loop into my methods so that after the code is executed it will run a best 2/3 games?
To my understanding, I know that I must use a loop in each method. Where the input from the user will be different and the cpu will generate another random move.
*Note: I'm not asking for a direct solution but for something conceptual as to what would be a good approach to this problem.
Below is my code:
package rpsmethods;
import java.util.Scanner;
import java.util.Random;
public class RPSMethods {
public static void displayOpeningMessage() {
System.out.println("Welcome to RPS Game 2.0!");
}
public static int getUserMove() {
Scanner input = new Scanner(System.in);
System.out.print("Select scissors (0), rock (1), or scissors (2): ");
int choice = 0;
if (input.hasNextInt()) {
choice = input.nextInt();
switch (choice) {
case 0:
System.out.println("You chose scissor!");
break;
case 1:
System.out.println("You chose rock!");
break;
case 2:
System.out.println("You chose paper!");
break;
default:
System.out.println("Not a valid input!");
System.out.print("Select scissors (0), rock (1), or scissors (2): ");
choice = input.nextInt();
}
}
return choice;
}
public static int getCPUMove() {
Random rnd = new Random();
int CPUMove = rnd.nextInt(3);
switch (CPUMove) {
case 0:
System.out.println("CPU chose scissor!");
break;
case 1:
System.out.println("CPU chose rock!");
break;
case 2:
System.out.println("CPU chose paper!");
break;
}
return CPUMove;
}
public static void determineWinner(int user, int cpu) {
//User win scenarios
if (user == 0 && cpu == 2) {
System.out.println("You win, Scissors beat Paper!");
} else if (user == 1 && cpu == 0) {
System.out.println("You win, Rock beats Scissors!");
} else if (user == 2 && cpu == 1) {
System.out.println("You win, Paper beats Rock!");
}
//Cpu win scenarios
if (user == 0 && cpu == 1) {
System.out.println("You lose, Rock beats Scissors!");
} else if (user == 1 && cpu == 2) {
System.out.println("You lose, Paper beats Rock!");
} else if (user == 2 && cpu == 0) {
System.out.println("You lose, Scissor beats Paper!");
}
//Draw scenarios
if (user == 0 && cpu == 0) {
System.out.println("You and CPU chose Scissor, it's a draw!");
} else if (user == 1 && cpu == 1) {
System.out.println("You and CPU chose Rock, it's a draw!");
} else if (user == 2 && cpu == 2) {
System.out.println("You and CPU chose Paper, it's a draw!");
}
}
public static void main(String[] args) {
displayOpeningMessage();
int userWinner = getUserMove();
int CpuWinner = getCPUMove();
determineWinner(userWinner, CpuWinner);
}
}
You can define two static variables to check the final winner in your
class:
static int cpuScore = 0;
static int humanScore = 0;
Then, you can set a value for that variables inside determineWinner like this:
if (CPU wins)
cpuScore++
else
humanScore++;
Then you can put your top level steps inside a loop like this:
while (cpuScore < 2 && humanScore < 2) {
...
}
Related
I am working on a "Rock, Paper, Scissors" game for my intro java class. Here is the prompt: Create a game of "Rock, Paper, Scissors" where the computer randomly chooses rock, paper, or scissors. Let the user enter a number of 1, 2, or 3, each representing one of three choices. Determine a winner. Game should ask the user to play again and continue if yes and stop if no. Once the user stops playing the program should print the total number of wins.
I am having issues with declaring my variables in the correct places since I am trying to use a method so I can call it to play the game again.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"yes\" or \"no\"");
input.next();
String answer = input.next();
}
public static int letsPlay()
{
int cMove;
int userMove = 0;
int cScore = 0;
int pScore = 0;
int tie = 0;
int rounds = 0;
Random r = new Random();
while (answer.equalsIgnoreCase("yes"))
cMove = r.nextInt(3)+1;
System.out.println("Choose your move!");
System.out.println("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ");
userMove = input.nextInt();
while(input.hasNextInt()) {
if (userMove!=1 && userMove!=2 && userMove!=3)
{
System.out.println("Invalid move. Try again.");
System.out.println("Enter your move: ");
input.nextInt();
}
}
if(userMove==1)
{
System.out.println("You have chosen Rock!");
}
else if(userMove==2)
{
System.out.println("You have chosen Paper!");
}
else if(userMove==3)
{
System.out.println("You have chosen Scissors!");
}
if (userMove == cMove)
{
System.out.println("Tie Game!");
System.out.println("");
tie++;
rounds++;
} else if (cMove==1 && userMove==3)
{
System.out.println("Computer chose Rock!");
System.out.println("Rock beats Scissors!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
else if (cMove==1 && userMove==2)
{
System.out.println("Computer chose Rock!");
System.out.println("Paper beats Rock!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==2 && userMove==3)
{
System.out.println("Computer chose Paper!");
System.out.println("Scissors beats Paper!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==2 && userMove==1)
{
System.out.println("Computer chose Paper!");
System.out.println("Paper beats Rock!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
else if (cMove==3 && userMove==1)
{
System.out.println("Computer chose Scissors!");
System.out.println("Rock beats Scissors!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==3 && userMove==2)
{
System.out.println("Computer chose Scissors!");
System.out.println("Scissors beats Paper!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
System.out.println("Would you like to play again?");
System.out.println("Answer \"yes\" or \"no\"");
input.next();
String yesorno = input.next();
if(yesorno.equalsIgnoreCase("yes"))
{
letsPlay();
}
else {
System.out.println ("Here are the final scores after " + rounds +" rounds:");
System.out.println ("You: "+ pScore + "Computer: "+ cScore + "Ties: " + tie);
}
}
}
Edited code so far, it says missing return statement from my letsPlay method:
Not sure how to proceed..
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"yes\" or \"no\"");
String answer = input.next();
letsPlay(answer);
}
public static int letsPlay(String answer)
{
int cMove;
int userMove = 0;
int cScore = 0;
int pScore = 0;
int tie = 0;
int rounds = 0;
Random r = new Random();
Scanner input = new Scanner(System.in);
cMove = r.nextInt(3)+1;
while (answer.equalsIgnoreCase("yes"))
System.out.println("Choose your move!");
System.out.println("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ");
userMove = input.nextInt();
while(input.hasNextInt()) {
if (userMove!=1 && userMove!=2 && userMove!=3)
{
System.out.println("Invalid move. Try again.");
System.out.println("Enter your move: ");
input.nextInt();
}
}
if(userMove==1)
{
System.out.println("You have chosen Rock!");
}
else if(userMove==2)
{
System.out.println("You have chosen Paper!");
}
else if(userMove==3)
{
System.out.println("You have chosen Scissors!");
}
if (userMove == cMove)
{
System.out.println("Tie Game!");
System.out.println("");
tie++;
rounds++;
} else if (cMove==1 && userMove==3)
{
System.out.println("Computer chose Rock!");
System.out.println("Rock beats Scissors!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
else if (cMove==1 && userMove==2)
{
System.out.println("Computer chose Rock!");
System.out.println("Paper beats Rock!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==2 && userMove==3)
{
System.out.println("Computer chose Paper!");
System.out.println("Scissors beats Paper!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==2 && userMove==1)
{
System.out.println("Computer chose Paper!");
System.out.println("Paper beats Rock!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
else if (cMove==3 && userMove==1)
{
System.out.println("Computer chose Scissors!");
System.out.println("Rock beats Scissors!");
System.out.println("Player Wins!");
pScore++;
rounds++;
}
else if (cMove==3 && userMove==2)
{
System.out.println("Computer chose Scissors!");
System.out.println("Scissors beats Paper!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
System.out.println("Would you like to play again?");
System.out.println("Answer \"yes\" or \"no\"");
input.next();
answer = input.next();
if(answer.equalsIgnoreCase("yes"))
{
main(null);
}
else {
System.out.println ("Here are the final scores after " + rounds +"
rounds:");
System.out.println ("You: "+ pScore + "Computer: "+ cScore + "Ties: "
+ tie);
}
}
}
You aren't passing the String answer to your letsPlay() method and that's because your letsPlay() method can't take a String as a parameter because it is defined without parameters being passed. A solution to this problem is to change the method definition to require a String variable.
public static int letsPlay()
turns into
public static int letsPlay(String userInput)
then inside your method you use the variable userInput instead of String answer in the letsPLay(String userInput) method.
The next issue you run into is you're calling the method again within the method. This is called recursion and it's perfectly legal, however it is not ideal in this circumstance. You should exit the game once it's over and ask the user in your main() method if they'd like to play again.
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
do
{
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"yes\" or \"no\"");
String answer = input.nextLine();
letsPlay(answer);
}while(answer.equalsIgnoreCase("yes"));
}
Firstly, in your main method one input.next() is extra and of no use so remove it.
Now write a statement in main method as follows after String answer = input.next();
:
letsPlay(answer);
Put a parameter in letsPlay() method as follows:
public static void letsPlay(String answer) {
//Your code..........
//Some last edits...
Scanner input = new Scanner(System.in);
answer = input.next();
if(!(answer.equalsIgnoreCase("yes")))
{
System.out.println ("Here are the final scores after "+rounds+"
rounds:");
System.out.println("You:"+pScore+"Computer: "+cScore+"Ties: "+tie);
}
}
No required extra method for calling any line.
You can call main
Move codes to main from letsPlay method.
remove: letsPlay()
use: main(null)
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"yes\" or \"no\"");
input.next();
String answer = input.next();
// moved codes to following place from letsPlay
int cMove = 0;
...
if(yesorno.equalsIgnoreCase("yes"))
{
main(null); // changed with letsPlay()
}
...
}
}
cMove not initilazed exception occurred. So use this:
int cMove = 0;
Now, any errors not occurred.
Move the Scanner object inside the constructor. Currently you have it outside and your code does not know what it is.
Here is the modified portion of your code:
public static int letsPlay()
{
int cMove;
int userMove = 0;
int cScore = 0;
int pScore = 0;
int tie = 0;
int rounds = 0;
Random r = new Random();
Scanner input = new Scanner(System.in); // move the input object inside the constructor
Hope it helps.
There are many errors in your code. You can check out the comments in the code for a proper understanding of the code.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
// initialising variable to 0 for score calculation
int cScore = 0;
int pScore = 0;
int tie = 0;
int rounds = 0;
Scanner input = new Scanner(System.in);
System.out.println("Would you like to play \"Rock, Paper, Scissors?\"");
System.out.println("Answer \"Yes\" or \"No\"");
String answer = input.next();
if (answer.equalsIgnoreCase("yes")) {
// Calling method letsPlay with arguments answer, cScore, pScore, tie, rounds
// initially cScore = pScore = tie = rounds = 0
letsPlay(answer, cScore, pScore, tie, rounds);
}
}
// letsPlay Method
public static void letsPlay(String answer, int cScore, int pScore, int tie, int rounds) {
int cMove;
int userMove;
Random r = new Random();
Scanner input = new Scanner(System.in);
// loop untill user chose no
while (true) {
// to get random move of computer on every iteration
cMove = r.nextInt(3) + 1;
System.out.println("--------------------------------------------------");
System.out.println("Choose your move!");
System.out.println("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ");
userMove = input.nextInt();
// loop until user input number 1 or 2 or 3
while (userMove != 1 && userMove != 2 && userMove != 3) {
System.out.println("Invalid move. Try again.");
System.out.println("--------------------------------------------------");
System.out.println("Choose your move: ");
System.out.println("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ");
userMove = input.nextInt();
}
// Print statement for user move
if (userMove == 1) {
System.out.println("You have chosen Rock!");
} else if (userMove == 2) {
System.out.println("You have chosen Paper!");
} else {
System.out.println("You have chosen Scissors!");
}
// Print statement for computer move
if (cMove == 1) {
System.out.println("Computer chose Rock!");
} else if (cMove == 2) {
System.out.println("Computer chose Paper!");
} else {
System.out.println("Computer chose Scissors!");
}
// Winning, Loosing and Tie conditions
// increment round to 1 every time
// increment the winner, looser or tie on every iteration
if (userMove == cMove) {
System.out.println("Tie Game!");
tie++;
rounds++;
} else if (cMove == 1 && userMove == 3) {
System.out.println("Rock beats Scissors!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
} else if (cMove == 1 && userMove == 2) {
System.out.println("Paper beats Rock!");
System.out.println("Player Wins!");
pScore++;
rounds++;
} else if (cMove == 2 && userMove == 3) {
System.out.println("Scissors beats Paper!");
System.out.println("Player Wins!");
pScore++;
rounds++;
} else if (cMove == 2 && userMove == 1) {
System.out.println("Paper beats Rock!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
} else if (cMove == 3 && userMove == 1) {
System.out.println("Rock beats Scissors!");
System.out.println("Player Wins!");
pScore++;
rounds++;
} else if (cMove == 3 && userMove == 2) {
System.out.println("Scissors beats Paper!");
System.out.println("Computer Wins!");
cScore++;
rounds++;
}
// Asking again to play or not
System.out.println("\nWould you like to play again?");
System.out.println("Answer \"Yes\" or \"No\"");
answer = input.next();
if (answer.equalsIgnoreCase("yes")) {
// If yes the call letsPlay(answer, cScore, pScore, tie, rounds);
// But this time value of cScore, pScore, tie, rounds is changed
// according to conditions
letsPlay(answer, cScore, pScore, tie, rounds);
} else {
// Print if user says didn't want to play again
System.out.println("==========================================");
System.out.println("\nHere are the final scores after " + rounds + " rounds:");
System.out.println("You : " + pScore + "\nComputer : " + cScore + "\nTies : " + tie);
}
// Exit if user didn't want to play again
break;
}
}
}
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.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I wanted to lead this question by letting everyone know that this is my first time on stack overflow so if I do not conform to question-asking standards please let me know.
I'm making a program that plays Rock, Paper, Scissors with you, and right as I was approaching the back end of the project this error came up:
Exception in thread "main" java.lang.NullPointerException
at RockPaperScissors.getPlayerThrow(RockPaperScissors.java:93)
at RockPaperScissors.main(RockPaperScissors.java:26)
I'm not sure where I would be using null, but thats what you're here for.
Here is the entire project compiled as it currently is:
public class RockPaperScissors {
//sets the constants
static final int ROCK = 1;
static final int PAPER = 2;
static final int SCISSORS = 3;
//creates some variables
static int playerThrow, computerThrow, result, timesPlayed, playerWins, computerWins;
static String playAgain;
static Scanner fru;
/*
* The Results
* 0 = tie
* 1 = Player win
* 2 = Computer win
*/
public static void main(String[] args) {
//this do while loop is the whole game
do {
//decides the throws of the players
playerThrow = getPlayerThrow();
computerThrow = (int)(Math.random() * 3 + 1);
switch(playerThrow) {
//compares and displays the computer and player
//choices if the player chooses rock
case ROCK:
switch(computerThrow) {
case ROCK:
result = 0;
System.out.println("You threw rock and the computer threw rock!");
break;
case PAPER:
result = 2;
System.out.println("You threw rock and the computer threw paper!");
break;
case SCISSORS:
result = 1;
System.out.println("You threw rock and the computer threw scissors!");
break;
} break;
//compares and displays the computer and player
//choices if the player throws paper
case PAPER:
switch(computerThrow) {
case ROCK:
result = 1;
System.out.println("You threw paper and the computer threw rock!");
break;
case PAPER:
result = 2;
System.out.println("You threw paper and the computer threw paper!");
break;
case SCISSORS:
result = 3;
System.out.println("You threw paper and the computer threw scissors!");
break;
} break;
//compares and displays the computer and player
//choices if the player throws scissors
case SCISSORS:
switch(computerThrow) {
case ROCK:
result = 2;
System.out.println("You threw scissors and the computer threw rock!");
break;
case PAPER:
result = 1;
System.out.println("You threw scissors and the computer threw paper!");
break;
case SCISSORS:
result = 0;
System.out.print("You threw scissors and the computer threw scissors!");
break;
} break;
}
timesPlayed ++;
// will compare and decide the winner of the two players
finish();
} while (timesPlayed < 3);
}
public static int getPlayerThrow() {
//prompts weapon choice and stores said choice
System.out.println("Choose your weapon of choice:\n(1 for rock, 2 for paper, 3 for scissors)");
int choice = fru.nextInt();
//checks for validity and returns the choice
if (choice != 1 && choice != 2 && choice != 3) {
System.out.print("Not a valid input!\n Please try again: ");
choice = fru.nextInt();
}
return choice;
}
//compares and decides the winner of the two players
public static void finish() {
//displays the winner of the round accourding to aforementioned possible results
switch(result) {
case 0:
System.out.println("Its a tie!"); break;
case 1:
System.out.println("You are victorious! Man over machine!");
playerWins++; break;
case 2:
System.out.println("The computer has taken the round! Technological singularity approaches!");
computerWins++; break;
}
//cheks if the match is over and displays messages accordingly
switch(timesPlayed) {
case 1: break;
case 2:
if (playerWins == 2 || computerWins == 2) {
if (playerWins == 2) {
System.out.println("You win the match! Congratulations!\nWould you like to play another match?\n(y for yes, n for no)");
timesPlayed = 5;
playAgain = fru.nextLine();
//checks for validity
if (playAgain != "y" || playAgain != "n") {
System.out.print("Not a valid input!\n Please try again: ");
playAgain = fru.nextLine();
}
}
else if (computerWins == 2) {
System.out.println("The computer wins the match!\nPlay again! I know you can beat it.\n(y for yes, n for no)");
timesPlayed = 5;
playAgain = fru.nextLine();
//checks for validity
if (playAgain != "y" || playAgain != "n") {
System.out.print("Not a valid input!\n Please try again: ");
playAgain = fru.nextLine();
}
}
} break;
//will happen for any amount of times played over 2
default:
if (playerWins == 2) {
System.out.println("You win the match! Congratulations!\nWould you like to play another match?\n(y for yes, n for no)");
playAgain = fru.nextLine();
//checks for validity
if (playAgain != "y" || playAgain != "n") {
System.out.print("Not a valid input!\n Please try again: ");
playAgain = fru.nextLine();
}
}
else if (computerWins == 2) {
System.out.println("The computer wins the match!\nPlay again! I know you can beat it.\n(y for yes, n for no)");
playAgain = fru.nextLine();
//checks for validity
if (playAgain != "y" || playAgain != "n") {
System.out.print("Not a valid input!\n Please try again: ");
playAgain = fru.nextLine();
}
}
}
}
}
I understand neither what the error means nor where it comes from. The only information that I have about it comes from skimming google for the error, but it is tough when the questions asked or examples posted are not specific to my project. I have taken multiple steps towards fixing it but none of them seem to do anything.
This could be a complex coding problem or a single character that I have missed, but any and all help is appreciated! Thank you!
I see plenty of places where you use the fru scanner but absolutely none where you actually initialise it. What you have basically boils down to:
import java.util.Scanner;
public class Test {
static Scanner fru;
public static void main(String[] arg) {
int x = fru.nextInt();
System.out.println(x+1);
}
}
and, when you run that, you'll see the exception. You'll need to do something like:
fru = new Scanner(System.in);
before you attempt to do any scanning. Until you do that, trying to dereference it will cause the exception you're getting. In other words, something like:
import java.util.Scanner;
public class Test {
static Scanner fru;
public static void main(String[] arg) {
fru = new Scanner(System.in);
int x = fru.nextInt();
System.out.println(x+1);
}
}
which runs successfully.
In terms of finding these problems in future, you would do well to look at the error message you're actually getting:
Exception in thread "main" java.lang.NullPointerException
at RockPaperScissors.getPlayerThrow(RockPaperScissors.java:93)
at RockPaperScissors.main(RockPaperScissors.java:26)
Despite the fact your error message doesn't quite match your code (line numbers are off by three), examining the stack trace to track down where and what the errors are is a vital skill.
In this case, it's the line:
int choice = fru.nextInt();
and you would therefore assume it's because fru has not been set correctly. From there, it a matter of tracking back to where you actually set fru to something useful. In this particular case, that doesn't exist so it's relatively easy to figure out.
I was tasked to create a java program that resembles rock, paper, scissors. I have written what I thought would work below. However, only when the user selects R or r (for rock) does it actually work properly. If the user selects s or p (scissors or paper) the code will completely break or give multiple answers. I have looked through the code and can't seem to find out why it's not working properly.
Also any suggestions on how to better write the switch portion of the code would be appreciated. I have a feeling the way I wrote it is not the proper way.
import java.util.Scanner;
public class Project_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int compVal = (int) (3 * Math.random()) + 1;
String compActual = "";
System.out.println("Welcome to Rock, Paper, Scissors!");
System.out.print("Enter r for rock, p for paper, or s for scissors: ");
String userOriginal = keyboard.nextLine();
userOriginal = (userOriginal.toUpperCase());
switch (userOriginal) {
case "r":
userOriginal = userOriginal;
break;
case "R":
userOriginal = userOriginal;
break;
case "p":
userOriginal = userOriginal;
break;
case "P":
userOriginal = userOriginal;
break;
case "s":
userOriginal = userOriginal;
break;
case "S":
userOriginal = userOriginal;
break;
default:
System.out.println("Invalid input, please try again!");
System.exit(1); // This will exit the program if invalid input is
// given. The 1 signifies that it ended with an
// error.
}
if (compVal == 1) {
compActual = "R";
} else if (compVal == 2) {
compActual = "P";
} else if (compVal == 3) {
compActual = "S";
}
if (compActual.equals(userOriginal)) {
System.out.println("It was a tie!");
} else if (compActual.equals("R"))
if (userOriginal.equals("S")) {
System.out.println("You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
}
if (userOriginal.equals("P")) {
System.out.println("You played Paper and I chose Rock: Paper covers Rock so you win this time!");
} else if (compActual.equals("S"))
if (userOriginal.equals("R")) {
System.out.println("You played Rock and I chose Sciccors: Rock crushes Scissors so you win this time");
}
if (userOriginal.equals("P")) {
System.out.println("You played Paper and I chose Scissors: Paper is cut by Scissors so I win this time!");
} else if (compActual.equals("P"))
if (userOriginal.equals("R")) {
System.out.println("Your played Rock and I chose Paper: Paper covers rock so I win this time!");
}
if (userOriginal.equals("S")) {
System.out.println("You played Scissors and I chose Paper: Scissors cuts Paper so you win this time!");
}
}
}
As suggested, you should clean up your code a little bit. Why not use numerical values instead of Strings for comparsion, like this:
int compVal = (int) (3 * Math.random()) + 1;
int userOriginal = 0;
String userInput = (keyboard.nextLine().toUpperCase());
switch (userInput) {
case "R":
userOriginal = 1;
break;
case "P":
userOriginal = 2;
break;
case "S":
userOriginal = 3;
break;
default:
System.out.println("Invalid input, please try again!");
System.exit(1); // This will exit the program
}
After that you can compare the user provided value with the generated one:
if (compVal == userOriginal) {
System.out.println("It was a tie!");
} else
{
//R
if (compVal == 1)
{
if (userOriginal == 2) {
System.out.println("You played Paper and I chose Rock: Paper covers Rock so you win this time!");
}
if (userOriginal == 3) {
System.out.println("You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
}
}
//P
if (compVal == 2)
{
if (userOriginal == 1) {
System.out.println("Your played Rock and I chose Paper: Paper covers rock so I win this time!");
}
if (userOriginal == 3) {
System.out.println("You played Scissors and I chose Paper: Scissors cuts Paper so you win this time!");
}
}
//S
if (compVal == 3)
{
if (userOriginal == 1) {
System.out.println("You played Rock and I chose Sciccors: Rock crushes Scissors so you win this time");
}
if (userOriginal == 2) {
System.out.println("You played Paper and I chose Scissors: Paper is cut by Scissors so I win this time!");
}
}
}
Also, remember to always close all the resources that you used:
keyboard.close();
You have multiple commands after an if-statement, but you're missing the {}.
For instance:
else if (compActual.equals("R"))
if (userOriginal.equals("S"))
{
System.out.println("You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
}
if (userOriginal.equals("P"))
{
System.out.println("You played Paper and I chose Rock: Paper covers Rock so you win this time!");
}
should be:
else if (compActual.equals("R"))
{
if (userOriginal.equals("S"))
{
System.out.println("You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
}
if (userOriginal.equals("P"))
{
System.out.println("You played Paper and I chose Rock: Paper covers Rock so you win this time!");
}
}
and, I'm sorry to say, you code needs cleaning up. For instance, you're using toUpperCase(), so no need to compare with lower case input.
First: what does should do your first switch (on userOrigignal values)?
If is is way to check if values is correct you have better way - create collection of possible values ("R", "P", "S") and check input against this collections:
private static final Collection<String> TYPES = new HashSet<>();
static {
TYPES.add("R");
TYPES.add("P");
TYPES.add("S");
}
private static boolean correctInput(String input) {
TYPES.contains(input.toUpperCase());
}
so you could replace this awful switch with simple call to function correctInput.
Next problem - you wrote totally wrong if's block: for example if (compActual.equals("R")) cases not surrounded with braces. So you checked R against S and after it simple entry for user "P"... It is better way to surround every if's body with braces - in this case you won't be confused by stylings and will see exact if's bodies.
And last problem - don't closed Scanner object. In current program it wouldn't bring any problem, but it is strongly recommended to always close resources.
PS you can make it much easelly with prepared table:
import java.util.*;
public class Project_2 {
private static final Map<String, Map<Integer, String>> TYPES = new HashMap<>();
static {
Map<Integer, String> subMap = new HashMap<Integer, String>();
subMap.put(0, "It was a tie!");
subMap.put(1, "You played Rock and I chose Scissors: Rock crushes Scissors so you win this time");
subMap.put(2, "Your played Rock and I chose Paper: Paper covers rock so I win this time!");
TYPES.put("R", subMap);
subMap = new HashMap<Integer, String>();
subMap.put(0, "You played Scissors and I chose Rock: Rock crushes Scissors so I win this time!");
subMap.put(1, "It was a tie!");
subMap.put(2, "You played Scissors and I chose Paper: Scissors cuts Paper so you win this time!");
TYPES.put("S", subMap);
subMap = new HashMap<Integer, String>();
subMap.put(0, "You played Paper and I chose Rock: Paper covers Rock so you win this time!");
subMap.put(1, "You played Paper and I chose Scissors: Paper is cut by Scissors so I win this time!");
subMap.put(2, "It was a tie!");
TYPES.put("P", subMap);
}
private static boolean checkInput(String input) {
TYPES.containsKey(input.toUpperCase());
}
public static void main(String[] args) {
int compVal = new Random().nextInt(3);
System.out.println("Welcome to Rock, Paper, Scissors!");
System.out.print("Enter r for rock, p for paper, or s for scissors: ");
String userOriginal = null;
try (Scanner keyboard = new Scanner(System.in)) {
userOriginal = keyboard.nextLine();
}
if (!checkInput(userOriginal)) {
System.out.println("Invalid input, please try again!");
System.exit(1); // This will exit the program if invalid input is
// given. The 1 signifies that it ended with an
// error.
}
System.out.println(TYPES.get(userOriginal, compVal));
}
}
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*/
}
}
}