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.
Related
I need to create a program that asks the user for a string value and returns a string value of "rock" "paper" or "scissors" if the input was "r" "p" or "s" If the user typed in something different.
package loopsGamesProject;
import java.util.Scanner;
public class LoopsGamesProject_RockPaperScissors {
public static void main(String[] args) {
String in="-";
Scanner input= new Scanner(System.in);
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in=input.next();
if(in=="r"||in=="p"||in=="s"){
if(in=="r"){
in="Rock";
}
if(in=="p"){
in="Paper";
}
if(in=="s"){
in="Scissors";
}
while(in!="r"||in!="p"||in!="s") {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in=input.next();
if(in=="r"||in=="p"||in=="s"){
if(in=="r"){
in="Rock";
}
if(in=="p"){
in="Paper";
}
if(in=="s"){
in="Scissors";
}
}
}
input.close();
System.out.print(in);
}
}
}
The issue is, it will ask for a variable, but the terminate itself. I've tried adding an "out" variable. When I tried to do this using a do while loop, it kept asking for an input but never returned anything. I can't find the issue.
When you compare Strings in java, you need to use the .equals() method instead of the == function. This rule applies for all objects in java, String inclusive.
EG:
if (in.equals("r"))
//Rock!
You also need to replace the != and add a break statement to exit the loop. Something like this will do:
while (!(in.equals("r") || in.equals("p") || in.equals("s"))) {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in = input.next();
if (in.equals("r") || in.equals("p") || in.equals("s")) {
if (in.equals("r"))
in = "Rock";
else if (in.equals("p"))
in = "Paper";
else
in = "Scissors";
break;
}
}
EDIT: The above prompts twice. This will fix it:
public static void main(String[] args) {
String in = "";
Scanner input = new Scanner(System.in);
while (!(in.equals("Rock") || in.equals("Paper") || in.equals("Scissors"))) {
System.out.print("Enter 'r' for rock, and 'p' for paper,'s' for scissors:");
in = input.next();
if (in.equals("r") || in.equals("p") || in.equals("s")) {
if (in.equals("r")) {
in = "Rock";
}
if (in.equals("p")) {
in = "Paper";
}
if (in.equals("s")) {
in = "Scissors";
}
break;
}
}
input.close();
System.out.print(in);
}
As has been mentioned, you need to compare String equality using the String.equals(Object anObject) - alternatively you may use others methods (compareTo), but the == operator will not suffice (See here why).
On top of this, when you match the String you overwrite the String with the full word - in = 'r'; -> in = 'Rock';. But the condition you use to loop will only terminate when in is r, p or s specifically.
Further, you have some duplicated code there that could be reduced significantly. This is not a bug, but this can become very difficult to manage very quickly.
All things considered:
while (true) {
// Get the next input
in = input.next();
// Maps the word to the character
// If a word was not mapped, try again.
if (in.equals("r"))
in = "Rock";
else if (in.equals("p"))
in = "Paper";
else if (in.equals("s"))
in = "Scissors";
else
continue;
// Terminate the loop as you can infer a match was found.
break;
}
The errors I am getting are "answer cannot be resolved". 1/4th of the way down the page. Looked online still don't see what it should be. Would it be easier to use the while loop instead? skipping the do loop completely?
import java.util.Scanner;
public class RPSS{
//Main method
public static void main(String[ ] argc)
{
Scanner tnt = new Scanner(System.in);
String computerHand; // string variable for computer choice
String userHand; // string variable for user choice
// do loop begining
do
{
computerHand = computerHand();
userHand = userHand();
String winner = getWinner(computerHand, userHand);
System.out.println(winner);
System.out.print("User picks" + userHand );
System.out.println("Computer picks " + computerHand );
System.out.println("play again?");
String answer = tnt.next();
//Condition for the do-while loop HERE IS THE ERROR LOCATION
}while (!answer.Equals("No") && (!answer.Equals("no"))); //condition for while loop
String answer = tnt.next();
}
public static String userHand(){ //method for users choice in the game
//prints message to user giving them choices
System.out.println("Lets play rock paper scissors");
System.out.println("1. Rock ");
System.out.println("2. Paper ");
System.out.println("3. Scissors ");
int userChoice; // user choice variable in this method
Scanner tnt = new Scanner(System.in); // creates instance of scanner class
userChoice = tnt.nextInt(); //reads user input
return getChoice(userChoice); //returns user choice to master choice
}
public static String computerHand() //method for computer generated choice
{
int computernum = (int)(Math.random() * (( 3) + 1));
return getChoice(computernum);
}
public static String getChoice(int num) //method recieving both computer hand and user hand
{
// if statements to place the correct choice
String choice = "";
if (num == 1){
choice = "rock";
}
else if(num == 2){
choice = "paper";
}
else if(num == 3){
choice = "scissors";
}
return choice;
}
// Method determing the winner
public static String getWinner(String computerChoice, String userChoice)
{
computerChoice = computerHand(); //places computerChoice variable in computerhand
userChoice = userHand(); //does same for user choice
String winner="";
System.out.println( " the comp chose" + computerChoice);
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println("The computer"); }
else if (userChoice.equals("Paper") && computerChoice.equals("Scissors")){
System.out.println(" The computer wins");
}
else if (userChoice.equals("Scissors") && computerChoice.equals("Rock")){
System.out.println(" The computer wins ");
}
else if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println(" The computer wins ");
}
if (userChoice.equals(computerChoice))
{
System.out.println(" There is no winner");
}
return winner;
}
}
Use tnt.next() which returns the next string. there is no such thing as nextString().
Also, add return winner; at the end of getwinner method.
You declared answer inside the braces of your do and then tried to use it outside the braces. Once you left the braces, the variable was out of scope.
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.
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.
I'm trying to add error handling to my java program if anything but the options and String/char are entered. I mainly need it for if a String is entered. I've tried to do the while(true) but I don't really understand that. I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. So I just need help adding error handling to my program. Thanks!
here's my code
import java.util.*;
public class HeroesVersusMonsters
{
private static Hero hero;
private static Monster monster;
private static Random rand = new Random();
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do
{
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
int choice = kb.nextInt();
kb.nextLine();
while (choice < 1 && choice > 4 )
{
System.out.println("\n" + choice + " is not an option. Please try again.");
System.out.print("Choice --> ");
choice = kb.nextInt();
kb.nextLine();
System.out.println();
}
switch (choice)
{
case 1:
hero = new Warrior();
break;
case 2:
hero = new Sorceress();
break;
case 3:
hero = new Thief();
break;
case 4:
hero = new Snake();
break;
}
switch (rand.nextInt(3))
{
case 0:
monster = new Ogre("Shrek the Ogre");
break;
case 1:
monster = new Skeleton("Bones the Skeleton");
break;
case 2:
monster = new Gremlin("Dobby the Gremlin");
break;
}
System.out.println();
System.out.println(hero.name + ", you will be fighting against " + monster.getName() + "!!!");
System.out.println();
while (hero.getHits() > 0 && monster.getHits() > 0)
{
hero.attack(monster);
monster.attack(hero);
}
System.out.print("Would you like to play again? (yes / no) ");
String play = kb.nextLine().toLowerCase();
play = play.trim();
if (play.equals("no"))
break;
else
System.out.println();
}
while (true);
}
}
Please look closly to your condition of inner while loop.
while (choice < 1 && choice > 4 )
Means loop will work until choice<1 and choice>4 remains true.
Is it exactly what you want?
I think No because what if input is 5 it is true for >4 but false for <1 what you want is you need to loop things until user enters correct input.
Am I right?
So what you need to do is just change condition like this
while(choice<1 || choice>4)
As Jared stated.
One more thing I want to suggest you don't you think you should break; external loop while user enters wrong input.(No problem)
You can do one this also.
ArrayList<Integer> ar=new ArrayList<Integer>(4);
ar.add(1);
ar.add(2);
ar.add(3);
ar.add(4);
while(true)
{
if(ar.contains(choice))
{
//Go On
}
else
{
//Print old stuff
}
}
Here is what your main method should look like:
public static void main(String ...args){
final Scanner scanner = new Scanner(System.in);
while(true){
final Hero hero = promptHero(scanner);
final Monster monster = getRandomMonster();
fight(hero, monster);
if(!playAgain(scanner))
break;
}
}
Now write the static methods promptHero, getRandomMonster, fight, and playAgain (which should return true if you want to play again).
Here is what your promptHero method should look like (to properly handle bad input):
private static Hero promptHero(final Scanner scanner){
while(true){
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
try{
final int choice = scanner.nextInt();
if(choice < 1 || choice > 4)
System.out.println("\n" + choice +
" is not an option. Please try again.");
else
return getHero(choice); //return the hero
} catch(InputMismatchException ime){
final String line = scanner.nextLine();// need to advance token
System.out.println("\n" + line +
" is not an option. Please try again.");
}
}
}
private static Hero getHero(final int choice){
switch (choice){
case 1:
return new Warrior();
case 2:
return new Sorceress();
case 3:
return new Thief();
case 4:
return new Snake();
}
return null;
}
You should check out the Java regex:
if(choice.toString().matches("[0-9]+"))
{
//continue
}
else
{
//error message
}