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.
Related
whenever I run this code, if I type a string as my input, I get an error on line 11. Help? I am not sure how to run an else statement or something asking what if they put a string rather than an integer (choice variable). I am new, so much help would be appreciated!
Here is my code:
import java.util.Scanner;
public class rockPaper {
public static void main(String args[]) {
System.out.println("Hello world");
int rock = 0;
int paper = 1;
int scissors = 2;
Scanner input = new Scanner(System.in);
System.out.println("Rock, Paper, or Scissors(0, 1, or 2)? Enter your integer: ");
int choice = input.nextInt();
int aIChoice = (int) (Math.random() * 3);
if (choice == rock) {
switch (aIChoice) {
case 0:
System.out.println("AI chose rock.");
System.out.println("Rock ties with rock!");
break;
case 1:
System.out.println("AI chose paper.");
System.out.println("Fail. Paper trumps rock.");
break;
case 2:
System.out.println("AI chose scissors.");
System.out.println("You win! Rock trumps scissors.");
break;
default:
break;
}
} else if (choice == paper) {
switch (aIChoice) {
case 0:
System.out.println("AI chose rock.");
System.out.println("You win! Paper trumps rock.");
break;
case 1:
System.out.println("AI chose paper.");
System.out.println("Paper ties with paper!");
break;
case 2:
System.out.println("AI chose scissors.");
System.out.println("Fail. Scissors trumps paper.");
break;
default:
break;
}
} else if (choice == scissors) {
switch (aIChoice) {
case 0:
System.out.println("AI chose rock.");
System.out.println("Fail. Rock trumps scissors.");
break;
case 1:
System.out.println("AI chose paper.");
System.out.println("You win! Scissors trumps paper.");
break;
case 2:
System.out.println("AI chose scissors.");
System.out.println("Scissors ties with scissors!");
break;
default:
break;
}
} else {
System.out.println("Nope!");
}
input.close();
}
}
As stated above, if I run the code, and I type in any letters(a string), I get an error referencing to line number eleven. I am not sure what I should do, because obviously as I've mentioned adding an else statement to all of this does not ensure the "nope" if they entered a string.
Usually you would not accept a string input. If you really need to for some reason, you could replace the input line with String choice = input.next() then do whatever tests you need to with it. After you confirm it's the input you want refer to this post to convert from a String to int.
Not quite sure what do you expect in case user provides invalid input, but, I think, reasonable option would be to check the input and print error message to the user if input is not a valid integer. For this just add this code below instead of this line in your code: int choice = input.nextInt();
int choice = -1;
if (input.hasNextInt()) {
choice = input.nextInt();
} else {
System.out.println("Please provide valid integer input: Rock, Paper, or Scissors(0, 1, or 2)?");
}
P.S. Also it would be good to check if your integer is in range [0,2].
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) {
...
}
I made a Rock Paper Scissors game for my CS class (senior in highschool) and the shell file my teacher gave me noted that I have to put the do while loop in the runner, but I don't see why? My code works, but she said it'd be better to write it in the runner? Why? Also, how can I write it more efficiently? (Note: I'm a total beginner, and prior to taking this class, had no knowledge of coding. Haven't learned recursion yet.)
my code:
import java.util.Random;
import java.util.Scanner;
public class RockPapersScissors {
private String user;
private int computer;
public RockPapersScissors(){
setPlayers(" ");
}
public RockPapersScissors(String s){
setPlayers(s);
}
public void setPlayers(String s){
user=s;
}
public void play(){
Scanner keyboard = new Scanner(System.in);
Random num = new Random();
int numUser = 0;
String playAgain = "";
do{
System.out.print("Rock-Paper-Scissors - pick your weapon[R,P,S] :: ");
user = keyboard.next();
System.out.println("player has "+ user);
switch(user){
case "R": numUser = 0; break;
case "P": numUser = 1; break;
case "S": numUser = 2; break;
case "r": numUser = 0; break;
case "p": numUser = 1; break;
case "s": numUser = 2; break;
default: System.out.println("Please enter a valid choice. Restart game.\n"); continue;
}
computer = num.nextInt(3);
switch(computer){
case 0: System.out.println("computer has R"); break;
case 1: System.out.println("computer has P"); break;
case 2: System.out.println("computer has S"); break;
}
if(numUser == computer){
System.out.println("!Draw Game!");
}else if(numUser == 0){
if(computer == 1){
System.out.println("!Computer Wins <<Paper Covers Rock>>!");
}if(computer == 2){
System.out.println("!Player Wins <<Rock Breaks Scissors>>!");
}
}else if(numUser == 1){
if(computer == 2){
System.out.println("!Computer Wins <<Scissors cuts paper>>!");
}if(computer == 0){
System.out.println("!Player Wins <<Paper Covers Rock>>!");
}
}else if(numUser == 2){
if(computer == 0){
System.out.println("!Computer Wins <<Rock Breaks Scissors>>!");
}if(computer == 1){
System.out.println("!Player Wins <<Scissors cuts paper>>!");
}
}
System.out.print("\nDo you want to play again? ");
playAgain = keyboard.next();
System.out.println("\n");
}while(playAgain.equals("y") || playAgain.equals("yes") || playAgain.equals("Y"));
System.out.println("Goodbye.");
keyboard.close();
}
}
my runner:
public class RPSRunner {
public static void main(String[] args) {
RockPapersScissors test = new RockPapersScissors();
test.play();
}
}
It all depends on the notion of what a "game" is. If a game is assumed to be a single round of RPS, with no keeping of score, then the teacher's prescribed solution would be good.
However, as soon as you need to retain some form of session state between rounds, such as a score, then you would have to make a design decision: Does the runner contain the logic to keep score, or does the game? Typically, one would have the game keep score, and the runner should know as little as possible about the internal logic of the game.
In another case, you may be asked to expand the runner so that you can choose between two different games. The second game might be "Black Jack", in which case you not only need to keep score, but also keep track of which cards have been played. As you can see the, the complexity of the runner can grow needlessly with your teacher's approach.
The teacher should have given you better requirements, or you should have asked.
By the way, this happens all the time in the real world.
I would say that each round of Rock/Paper/Scissors is independent of all the others. I would have written a single method that took in player 1 and 2 values and returned a winner. Get that to work and then put it in the game loop to play over and over again.
There could be a second overloaded version of play() method with an embedded computer player that would randomly choose and call the two-player version.
Perhaps that is what your teacher meant, too. Why not ask them instead of making us read his/her mind? You can learn a lot using the Socratic method.
Don't worry about efficiency; it doesn't matter for such a trivial application. Make it run; make it run correctly; make it run fast.
Whenever I run it, it seems that the loop to continue playing works, but the game outcome is not outputting correctly whenever the conputerChoose executes the randomGenerator. Please help. I'm new to java, and we are only suppose to use 3 methods - instructions, playGame and computerChoose. We are also suppose to use a user controlled loop to continue working. I can't seem to get this right and I still have to add a loop to count the number of time sthe game has been played, the number of times won and the number of times the computer won.
import java.util.*;
public class PRS {
public static Scanner kbd = new Scanner(System.in);
public static void instructions() {
System.out.println("\nThis is the popular game of paper, rock, scissors. Enter your"
+ "\nchoice by typing the word \"paper\", the word \"rock\" or the word"
+ "\n\"scissors\". The computer will also make a choice from the three"
+ "\noptions. After you have entered your choice, the winner of the"
+ "\ngame will be determined according to the following rules:"
+ "\n\nPaper wraps rock (paper wins)"
+ "\nRock breaks scissors (rock wins)"
+ "\nScissors cuts paper (scissors wins)"
+ "\n\nIf both you and the computer enter the same choice, then the game "
+ "\nis tied.\n");
}
public static int playGame(){
int outcome = 0;
System.out.print("Enter your choice: ");
kbd = new Scanner(System.in);
String player = kbd.nextLine().toLowerCase();
String computerChoice = computerChoose();
System.out.println("\nYou entered: " + player);
System.out.println("Computer Chose: " + computerChoose());
if(player.equals(computerChoose())){
outcome = 3;
}
else if (player.equals("paper") && computerChoice.equals("rock")){
outcome = 1;
}
else if (computerChoice.equals("paper") && player.equals("rock")){
outcome = 2;
}
else if (player.equals("rock") && computerChoice.equals("scissors")){
outcome = 1;
}
else if (computerChoice.equals("rock") && player.equals("scissors")){
outcome = 2;
}
else if (player.equals("scissors") && computerChoice.equals("paper") ){
outcome = 1;
}
else if (computerChoice.equals("scissors") && player.equals("paper")){
outcome = 2;
}
else if (player.equals("rock") && computerChoice.equals("paper") ){
outcome = 2;
}
else if (computerChoice.equals("rock") && player.equals("paper")){
outcome = 1;
}
return outcome;
}
public static String computerChoose(){
/*return "scissors";*/
Random generator = new Random();
String [] answer = new String [3];
answer [0]= "paper";
answer [1] = "rock";
answer [2] = "scissors";
return answer[generator.nextInt(3)];
}
public static void main(String[] args) {
kbd = new Scanner(System.in);
System.out.println("THE GAME OF PAPER, ROCK, SCISSORS:");
System.out.print("\nDo you need instructions (Y or N)? ");
String userPlay = kbd.nextLine();
if (userPlay.equalsIgnoreCase("y")){
instructions();
}
String answer;
do{
int result = playGame();
System.out.println(result);
switch (result){
case 1:
System.out.println("YOU WIN!");
break;
case 2:
System.out.println("Comp WINs!");
break;
case 3:
System.out.println("IT'S A TIE!");
break;
default:
}
System.out.print("\nPlay again ( Y or N)? ");
answer = kbd.nextLine();
}while(answer.equalsIgnoreCase("y"));
}
}
The first thing you need to do is only call computerChoose() once. Every time you are calling this method it is generating a new random number and hence a different answer. You should only call it once inside playGame() and assign it to a local variable.
E.g.
String computerChoice = computerChoose();
Then replace all of your other calls to computerChoose() with this variable name. This way you will display the one value and compare only the one value in your logic.
As for tracking other information such as the number of games, and the number of wins/losses, think about declaring a few more class variables (or local variables in the main method) which you can then assign, increment and read. You can do all this from within your do-while loop in the main method. No need for any additional loops.
In addition to Adam's answer, changing the do-while loop at the end to the following will resolve a few different issues.
String answer;
int winCount=0, lossCount=0, tieCount=0;
do{
int result = playGame();
switch (result){
case 1:
System.out.println("YOU WIN!");
winCount++;
break;
case 2:
System.out.println("Comp WINs!");
lossCount++;
break;
case 3:
System.out.println("IT'S A TIE!");
tieCount++;
break;
default:
}
System.out.print("\nPlay again ( Y or N)? ");
answer = kbd.nextLine();
}while(answer.equalsIgnoreCase("y"));
System.out.printf("Wins: %d, Losses: %d, Total plays: %d%n", winCount, lossCount, winCount+lossCount+tieCount);
You need to update result inside the while loop or else only the first game's results will be accurate.
This is just a simple rock paper scissors game I made with eclipse as a test and I already put one through this website earlier and got some answers but now I've run into a problem where I cannot find a winner?
package rockPaperScissors;
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String args[]) {
String playerChose;
String computerChose;
while(true) {
System.out.println("Welcome to rock paper scissors!");
System.out.println("Please enter \"rock\", \"paper\", or \"scissors\"");
Scanner playerChoice = new Scanner (System.in);
playerChose = playerChoice.nextLine();
Random computerChoice = new Random();
int computer = computerChoice.nextInt(3) + 1;
switch (computer) {
case 1:
computerChose = "rock";
System.out.println("Computer chose rock!");
break;
case 2:
computerChose = "paper";
System.out.println("Computer chose paper!");
break;
case 3:
computerChose = "scissors";
System.out.println("Computer chose scissors!");
}
computerChose = new String();
if (playerChose.equals("rock") && computerChose.equals("scissors") || playerChose.equals("paper") && computerChose.equals("rock") || playerChose.equals("scissors") && computerChose.equals("paper")) {
System.out.println("Player won!");
}
if(playerChose.equals(computerChose)) {
System.out.println("Game tied!");
}
if(computerChose.equals("rock") && playerChose.equals("scissors") || computerChose.equals("paper") && playerChose.equals("rock") || computerChose.equals("scissors") && computerChose.equals("paper")) {
System.out.println("Computer won!");
}
}
}
}
Tested and works
Initialize computerChose right away, so change
String computerChose; to String computerChose = "";
and take away the line computerChose = new String(); because it's setting the computerChoose String to an empty String after you initialized it in your switch cases.
Change your initial declaration of computerChose (before your while) to String computerChose = ""; and remove the line that reads computerChose = new String(); (after your switch).
After the while statement, computerChose is getting reset using computerChose = newString(). Hence, none of the conditions being tested in the if statements are equating to true.