Debugging my simple java game(Rock Paper Scissor) [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I created this program to run infinite times asking the user to enter a choice(rock or paper or scissor), which seems to work fine. The problem is no else ....if or if ....else statements are satisfied. Whatever input i give it just prints out the else statement in the else statement, (Enter a valid choice). I cant find the mistake i made so ill link my code below..... Thanks in advance.
import java.util.Scanner;
import java.util.Random;
public class apples {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
Random number = new Random();
String rps[] = {"rock", "paper", "scissor"};
String player;
String ai;
int rand, pscore=0, aiscore=0;
while(1 < 2){
System.out.println("Take your pick \nrock \npaper \nscissor");
player = input.nextLine();
rand = number.nextInt(3);
ai = rps[rand];
System.out.println(ai);
if(player == ai){
pscore+=0;
aiscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else{
if(player == "rock" && ai == "paper"){
aiscore+=1;
pscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "rock" && ai == "scissor"){
pscore+=1;
aiscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "paper" && ai == "rock"){
pscore+=1;
aiscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "paper" && ai == "scissor"){
aiscore+=1;
pscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "scissor" && ai == "rock"){
aiscore+=1;
pscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "scissor" && ai == "paper"){
aiscore+=0;
pscore+=1;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else{
System.out.println("Enter a valid choice");
System.out.print("\n");
continue;
}
}
}
}
}

Instead of :
if(player == "rock" && ai == "paper"){
...
}
Use
if(player.equals("rock") && ai.equals("paper")){
...
}
This will apply to all of your pieces of code which compare Strings.

In java, == tests for reference equality: if the two objects are actually the same object. Two strings holding the same characters will fail this check, which is what's happening in your logic.
See How do I compare strings in Java?

Related

How to loop a certain area of code after a wrong user input? (Java)

I have been working on a small Rock Paper Scissors game with Java, where the win or lose condition is based on whether the computer or the player wins five games. I am not sure how to get the program to loop at the user input should there be a wrong input.
Here is the code where I'm having this trouble
The section that I'm trying to loop is the portion with "else if (determination.equals("Y")) {"
import java.util.*;
public class Rock_Paper_Scissors {
public static void main(String arg[]) {
boolean loopGameStart = true;
while (loopGameStart) {
System.out.println("Welcome to Rock Paper Scissors, a game programmed "
+ "by Daniel Park. Would you like to start? (Y/N)");
Scanner userInput = new Scanner(System.in);
String determination = userInput.next();
if (determination.equals("N")) {
System.out.println("Please, do reconsider...");
loopGameStart = true;
} else if (determination.equals("Y")) {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
// 1 = Rock, 2 = Paper, 3= Scissor
int humanWinCount = humanWinCount();
int computerWinCount = computerWinCount();
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
Scanner userRPS = new Scanner(System.in);
int choiceRPS = userRPS.nextInt();
while ((humanWinCount < 5) && (computerWinCount < 5)) {
if (choiceRPS == 0) {
if (n == 1) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try Again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
} else if (choiceRPS == 1) {
if (n == 1) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
} else if (choiceRPS == 2) {
if (n == 1) {
System.out.println("LOSS");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
}
}
if (humanWinCount == 5) {
System.out.println("Congratulations, you win!!");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
}
if (computerWinCount == 5) {
System.out.println("Boohoo, you lost!!");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
}
} else {
System.out.println("I do not understand, please try again!");
}
}
}
public static int humanWinCount() {
int x = 0;
return x;
}
public static int computerWinCount() {
int c = 0;
return c;
}
}
Please, do not write everything in one main function, or repeat the same code everywhere, and etc.
I completely rebuild your code and also implemented the loop #Austin suggested. Now your should be working as you which or very close. Enjoy:
import java.util.*;
public class Rock_Paper_Scissors
{
public static void main( String arg[] )
{
Rock_Paper_Scissors game = new Rock_Paper_Scissors();
game.startLogic();
}
private Random rand;
private Scanner inputScanner;
private boolean loopGameStart;
private int humanWinCount;
private int computerWinCount;
public Rock_Paper_Scissors()
{
this.rand = new Random();
this.inputScanner = new Scanner( System.in );
this.loopGameStart = true;
humanWinCount = 0;
computerWinCount = 0;
}
public void startLogic()
{
System.out.print( "Welcome to Rock Paper Scissors, a game programmed by Daniel Park. " );
this.askUntilGetAnAnswer( "N" );
}
private int humanWinCount()
{
int x = 0;
return x;
}
private int computerWinCount()
{
int c = 0;
return c;
}
private void askUntilGetAnAnswer( String determination )
{
while( this.loopGameStart )
{
if( !determination.equals( "Y" ) )
{
System.out.println( "\nWould you like to start? (Y/N)" );
determination = this.inputScanner.next();
}
if( determination.equals( "N" ) )
{
System.out.println( "Please, do reconsider..." );
this.loopGameStart = false;
}
else if( determination.equals( "Y" ) )
{
this.processCoreGameLogic();
}
else
{
System.out.print( "I do not understand, please try again!" );
}
}
}
private void processCoreGameLogic()
{
int choiceRPS;
System.out.println( "Choose 0, 1, or 2 (Rock/Paper/Scissor)" );
// 1 = Rock, 2 = Paper, 3= Scissor
this.humanWinCount = this.humanWinCount();
this.computerWinCount = this.computerWinCount();
while( ( this.humanWinCount < 5 ) && ( this.computerWinCount < 5 ) )
{
try
{
choiceRPS = inputScanner.nextInt();
if( choiceRPS >= 0 && choiceRPS <= 2 )
{
this.playing( choiceRPS );
}
}
catch( InputMismatchException e )
{
System.out.print( "I do not understand, please try again!" );
inputScanner.next();
}
}
this.endGame();
}
private void endGame()
{
String contOrNot = "";
if( this.humanWinCount == 5 )
{
System.out.println( "\nCongratulations, you win!!" );
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
System.out.println( "Would you like to try again? (Y/N)" );
contOrNot = this.inputScanner.next();
}
if( this.computerWinCount == 5 )
{
System.out.println( "\nBoohoo, you lost!!" );
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
System.out.println( "Would you like to try again? (Y/N)" );
contOrNot = this.inputScanner.next();
}
if( contOrNot.equals( "N" ) )
{
System.out.println( "Okay, goodbye!!" );
this.loopGameStart = false;
}
else
{
askUntilGetAnAnswer( contOrNot );
}
}
private void playing( int choiceRPS )
{
int randomInteger = this.rand.nextInt( 3 ) + 1;
// choiceRPS 0 -> tie 1, loss 2, win 3
// choiceRPS 1 -> win 3, tie 1, loss 2
// choiceRPS 2 -> loss 2, win 3, tie 1
//
switch( choiceRPS*3 + randomInteger )
{
case 1:
case 5:
case 9:
{
show_tie();
break;
}
case 2:
case 6:
case 7:
{
show_loss();
break;
}
case 3:
case 4:
case 8:
{
show_win();
break;
}
default:
{
System.out.println( " I do not understand... Try again." );
System.out.println( " Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
System.out.println( " Computer: " + this.computerWinCount + " rounds won" );
System.out.println( " You: " + this.humanWinCount + " rounds won" );
}
}
}
private void show_loss()
{
System.out.println( "LOSS" );
System.out.println( "Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
this.computerWinCount = this.computerWinCount + 1;
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
}
private void show_win()
{
System.out.println( "WIN!!" );
System.out.println( "Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
this.humanWinCount = this.humanWinCount + 1;
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
}
private void show_tie()
{
System.out.println( "TIE!!" );
System.out.println( "Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
}
}
You can use a do while
int choiceRPS;
do{
choiceRPS = userRPS.nextInt();
}while(choiceRPS<0||choiceRPS>2);
Your logic looks very complex. It can be easily simplified as the game has only 3 outcomes other that a tie.
SCISSORS beats PAPER
PAPER beats ROCK
ROCK beats SCISSORS
So considering the inputs as 0, 1 and 2 representing Rock, Paper and Scissors respectively:
You need to keep track of two numbers. One is user entered choice
let's call it userChoice and another being computerChoice which
is computer's played choice. This computerChoice should be a
randomly chosen digit between 0 and 2 both inclusive.
Now, start comparing both the numbers to decide on the winner and
increment the respective counter (humanWinCount and
computerWinCount).
Stop the game and decide the winner when either the user or the
computer wins at least 5 rounds.
Hence, your gaming loop should be looking something like this:
while(true){
System.out.println();
/*
* If either one wins, break out of the game
* and decide the winner.
*/
if(humanWinCount == 5 || computerWinCount == 5){
break;
}
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
//Read user's choice
int userChoice = Integer.parseInt(sc.nextLine());
//Computer will play it's turn
int computerChoice = rand.nextInt(3);
//Start comparing player's choice vs Computer's choice
if(userChoice == computerChoice){
tieCount++;
showTieMessage();
}else if(userChoice == 0 && computerChoice == 1){
//User plays ROCK and computer plays PAPER
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 0 && computerChoice == 2){
//User plays ROCK and computer plays SCISSORS
humanWinCount++;
showHumanWinMessage();
}else if(userChoice == 1 && computerChoice == 0){
//User plays PAPER and computer plays ROCK
humanWinCount++;
showHumanWinMessage();
}else if(userChoice == 1 && computerChoice == 2){
//User plays PAPER and computer plays SCISSORS
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 2 && computerChoice == 0){
//User plays SCISSORS and computer plays ROCK
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 2 && computerChoice == 1){
//User plays SCISSORS and computer plays PAPER
humanWinCount++;
showHumanWinMessage();
}else{
System.out.println("Unrecougnized user input!!");
System.out.println("Please Enter correct values!!");
continue;
}
}
And the entire remodeled code should be looking something like this:
public class RockPepperScissor {
private Random rand;
private int humanWinCount;
private int computerWinCount;
private int tieCount; //Not Required, but still keeping in track.
public RockPepperScissor(){
rand = new Random();
humanWinCount = 0;
computerWinCount = 0;
tieCount = 0;
}
public void startGame(){
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Rock Paper Scissors, a game programmed by Daniel Park. Would you like to start? (Y/N)");
String userChoice = sc.nextLine();
if(userChoice.equalsIgnoreCase("Y")){
startGameLogic(sc);
}else{
if(userChoice.equalsIgnoreCase("N")){
System.out.println("Do you want to reconsider?? (Y/N)");
String secondChance = sc.nextLine();
if(secondChance.equalsIgnoreCase("Y")){
startGameLogic(sc);
}else{
System.exit(0);
}
}else{
System.out.println("Unable to identify your input!! Stopping the game!!");
System.exit(0);
}
}
sc.close();
}
public void startGameLogic(Scanner sc){
while(true){
System.out.println();
/*
* If either one wins, break out of the game
* and decide the winner.
*/
if(humanWinCount == 5 || computerWinCount == 5){
break;
}
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
//Read user's choice
int userChoice = Integer.parseInt(sc.nextLine());
//Computer will play it's turn
int computerChoice = rand.nextInt(3);
//Start comparing player's choice vs Computer's choice
if(userChoice == computerChoice){
tieCount++;
showTieMessage();
}else if(userChoice == 0 && computerChoice == 1){
//User plays ROCK and computer plays PAPER
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 0 && computerChoice == 2){
//User plays ROCK and computer plays SCISSORS
humanWinCount++;
showHumanWinMessage();
}else if(userChoice == 1 && computerChoice == 0){
//User plays PAPER and computer plays ROCK
humanWinCount++;
showHumanWinMessage();
}else if(userChoice == 1 && computerChoice == 2){
//User plays PAPER and computer plays SCISSORS
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 2 && computerChoice == 0){
//User plays SCISSORS and computer plays ROCK
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 2 && computerChoice == 1){
//User plays SCISSORS and computer plays PAPER
humanWinCount++;
showHumanWinMessage();
}else{
System.out.println("Unrecougnized user input!!");
System.out.println("Please Enter correct values!!");
continue;
}
}
}
public void showHumanWinMessage(){
System.out.println("YOU WON!!");
System.out.println("Your wins: " + humanWinCount);
System.out.println("Computer wins: " + computerWinCount);
System.out.println("Ties: " + tieCount);
}
public void showComputerWinMessage(){
System.out.println("YOU LOST!!");
System.out.println("Your wins: " + humanWinCount);
System.out.println("Computer wins: " + computerWinCount);
System.out.println("Ties: " + tieCount);
}
public void showTieMessage(){
System.out.println("Tie!!");
System.out.println("Your wins: " + humanWinCount);
System.out.println("Computer wins: " + computerWinCount);
System.out.println("Ties: " + tieCount);
}
public void decideWinner(){
if(humanWinCount > computerWinCount){
System.out.println();
System.out.println("Yippee!! You won the Game!!");
}else if(computerWinCount > humanWinCount){
System.out.println();
System.out.println("Oops!! You lost the Game!!");
System.out.println("Better Luck Next Time!!");
}
}
public static void main(String[] args) {
RockPepperScissor rps = new RockPepperScissor();
rps.startGame();
rps.decideWinner();
}
}
I hope this helps you in your learning activity.
So it's pretty much visible that the code is not modular and there are redundant statements in the code. They might still be there, since all I did was to fix the logic and make comments on the code for the changes introduced -
public class Rock_Paper_Scissors {
public static void main(String arg[]) {
boolean loopGameStart = true;
while (loopGameStart) {
System.out.println(
"Welcome to Rock Paper Scissors, a game programmed by Daniel Park. Would you like to start? (Y/N)");
Scanner userInput = new Scanner(System.in);
String determination = userInput.next();
switch (determination) {
case "N":
System.out.println("Please, do reconsider...");
loopGameStart = true; // you might not want the player to be trapped here, so change it to `false` rather
break;
case "Y":
/** 0 = Rock, 1 = Paper, 2 = Scissor */
int humanWinCount = 0;
int computerWinCount = 0;
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
Scanner userRPS = new Scanner(System.in);
int userChoice = userRPS.nextInt();
while ((humanWinCount < 5) && (computerWinCount < 5)) { // either of them reaches 5
int computerChoice = new Random().nextInt(3); // this is fun, no more static computer choice
if (userChoice == computerChoice) { // break quick if its a tie
System.out.println("TIE!!");
displayStats(computerWinCount, humanWinCount);
askChoice();
} else {
switch (userChoice) { //based on userChoice and computerChoice combination
case 0:
if (computerChoice == 1) {
System.out.println("LOSS!!");
displayStats(computerWinCount++,
humanWinCount); // incrementing the computerCount as well
askChoice();
} else if (computerChoice == 2) {
System.out.println("WIN!!");
displayStats(computerWinCount,
humanWinCount++); // incrementing the humanCount as well
askChoice();
}
break;
case 1:
if (computerChoice == 0) {
System.out.println("WIN!!");
displayStats(computerWinCount, humanWinCount++);
askChoice();
} else if (computerChoice == 2) {
System.out.println("LOSS!!");
displayStats(computerWinCount++, humanWinCount);
askChoice();
}
break;
case 2:
if (computerChoice == 0) {
System.out.println("LOSS");
displayStats(computerWinCount++, humanWinCount);
askChoice();
} else if (computerChoice == 1) {
System.out.println("WIN!!");
displayStats(computerWinCount, humanWinCount++);
askChoice();
}
break;
default:
System.out.println("I do not understand... Try again.");
displayStats(computerWinCount, humanWinCount);
askChoice();
break;
}
}
userChoice = userRPS.nextInt(); //next iteration input only required once
}
if (humanWinCount == 5) {
System.out.println("Congratulations, you win!!");
} else {
System.out.println("Boohoo, you lost!!");
}
displayStats(computerWinCount, humanWinCount);
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
break;
default:
System.out.println("I do not understand, please try again!");
break;
}
}
}
private static void askChoice() {
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
}
private static void displayStats(int computerWinCount, int humanWinCount) {
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
}
}
The code explanation would be something that I would leave on what you won't understand in it. So please ask further for anything that you might want to know about why it's being used.
If you need to loop certain code with conditional behaviour, try to use recursive parametric method and enclapsure the conditional parts code each into separate method. These methods will be called from the current recursion. Then call first-time recursion level from main method.
Pseudo-sample:
public int myRecursiveMethod_RPS (int aVariable)
{
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
...
// your own logic below - this is just sample
if (aVariable == 0)
return myRecursiveMethod_RPS(0);
else if (aVariable >= 0)
return myRecursiveMethod_RPS(aVariable);
else return aVariable;
}
Good article about recursion is here Recursion - Java or
here https://howtoprogramwithjava.com/java-recursion/
Try using a do/while loop. The code is run until a certain condition is no longer met, but at least it will be run once even if the condition is not true at the beginning. Using your first input as an example, it would look just like this:
String determination; // I move the variable determination outside so it is in the scope of the while.
do {
System.out.println(
"Welcome to Rock Paper Scissors, a game programmed by Daniel Park. Would you like to start? (Y/N)");
Scanner userInput = new Scanner(System.in);
determination = userInput.next();
} while (determination != "Y" || determination != "N");
//...
The code will at least be run once. If at anytime 'determination' equals "N" or "Y", it will go on with the rest of the code.
You can get more information from this website:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
As i already edited into addons_zz modular version of your program Perambulation: The Scanner that is used for userinput throws an InputMismatchException if you input e.g. "a" and the nextInt() Method of the Scanner is called. The Input "a" can't be cast to the type integer since its a character of the alphabet. A solution to this could look like(in your version of the code):
...
} else if (determination.equals("Y")) {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
// 1 = Rock, 2 = Paper, 3= Scissor
int humanWinCount = humanWinCount();
int computerWinCount = computerWinCount();
Scanner userRPS = new Scanner(System.in);
// loop until choiceRPS is 0, 1 or 2
int choiceRPS = 9;
boolean choiceRPSNotSet = true;
while(choiceRPSNotSet){
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
try
{
choiceRPS = userRPS.nextInt();
if( choiceRPS >= 0 && choiceRPS <= 2 )
{
choiceRPSNotSet = false;
}
}
catch( InputMismatchException e )
{
System.out.println( "I do not understand, please try again!" );
userRPS.next();
}
}
// loop until choiceRPS is 0, 1 or 2
while ((humanWinCount < 5) && (computerWinCount < 5)) {
...
So i added another while loop based on the condition that choiceRPS is set correctly.
if( choiceRPS >= 0 && choiceRPS <= 2 )
{
choiceRPSNotSet = false;
}
Only then the loop will be left which includes catching Exceptions since this part is located in the try/catch block.
Calling the userRPS.next() (or Scanner.next()) Method if an InputMismatchException occurs will clean the Input from the Scanner so that a new input can be read.
An alternative which i would recommend would be encapsulating the userinput into its own method like:
public static int choose(){
Scanner userRPS = new Scanner(System.in);
// loop until choiceRPS is 0, 1 or 2
int choiceRPS = 9;
boolean choiceRPSNotSet = true;
while(choiceRPSNotSet){
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
try
{
choiceRPS = userRPS.nextInt();
if( choiceRPS >= 0 && choiceRPS <= 2 )
{
choiceRPSNotSet = false;
}
}
catch( InputMismatchException e )
{
System.out.println( "I do not understand, please try again!" );
userRPS.next();
}
}
// loop until choiceRPS is 0, 1 or 2
return choiceRPS;
}
And calling this choose() method whenever necessary like:
...
} else if (determination.equals("Y")) {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
// 1 = Rock, 2 = Paper, 3= Scissor
int humanWinCount = humanWinCount();
int computerWinCount = computerWinCount();
int choiceRPS = choose();
while ((humanWinCount < 5) && (computerWinCount < 5)) {
if (choiceRPS == 0) {
if (n == 1) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = choose();
} else if (n == 2) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = choose();
...
Hope this helps! ^^
import java.util.*;
public class Rock_Paper_Scissors {
public static void main(String arg[]) {
boolean loopGameStart = true;
while (loopGameStart) {
System.out.println("Welcome to Rock Paper Scissors, a game programmed "
+ "by Daniel Park. Would you like to start? (Y/N)");
Scanner userInput = new Scanner(System.in);
String determination = userInput.next();
//1=THIS CHANGED TO IGNORE CASE N or n Y or y accepted
if (determination.equalsIgnoreCase("N")) {
System.out.println("Please, do reconsider...");
loopGameStart = true;
} else if (determination.equals("Y")) {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
// 1 = Rock, 2 = Paper, 3= Scissor
int humanWinCount = humanWinCount();
int computerWinCount = computerWinCount();
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
Scanner userRPS = new Scanner(System.in);
int choiceRPS = userRPS.nextInt();
while ((humanWinCount < 5) && (computerWinCount < 5)) {
if (choiceRPS == 0) {
if (n == 1) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try Again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
} else if (choiceRPS == 1) {
if (n == 1) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
} else if (choiceRPS == 2) {
if (n == 1) {
System.out.println("LOSS");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
}else{
//###################################THIS IS THE ADDED CODE
System.out.println("INVALID VALUE ENTER AGAIN");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
}
if (humanWinCount == 5) {
System.out.println("Congratulations, you win!!");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
}
if (computerWinCount == 5) {
System.out.println("Boohoo, you lost!!");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
}
} else {
System.out.println("I do not understand, please try again!");
}
}
}
public static int humanWinCount() {
int x = 0;
return x;
}
public static int computerWinCount() {
int c = 0;
return c;
}
}
Just a simple loop would do the trick :
Scanner answerScanner = new Scanner(System.in);
do{
char answer = answerScanner.next().charAt(0);
}while(answer != 'Y' && answer != 'N');
// Then do whatever you need to do
if(answer == 'Y'){
// Something
}else{
// Something else
}
Note that you could use answerScanner.next().toUpperCase().charAt(0) if you wanted to allow 'y' and 'n' as answers.

Inputted string also assigned to an integer?

I'm trying to make a rock-paper-scissors program that is a best two out of three where the computer randomly rolls a 0-2 and each of those are assigned to rock, paper, or scissors, and then it compares the userInput and counts a win for computer or player then adds it up.
BUT, I can't figure out how to make it that if user were to enter "scissors" the program would know that it's also assigned to 2 (For comparison purposes).
public static void main(String[] args) {
Random r = new Random();
int gameCount = 0;
int computerWins = 0;
int playerWins = 0;
int rock = 0;
int paper = 1;
int scissors = 2;
int playerChoice;
int computerChoice = r.nextInt(3);
System.out.println("Welcome to Rock Paper Scissors! Best 2 out of 3!");
while (gameCount >= 0 && gameCount < 3)
{
System.out.println("Enter \"Rock\", \"Paper\", or \"Scissors\"");
break;
}
playerChoice = userInput.nextInt()
//If player enters anything besides rock, paper, or scissors
if (playerChoice < 0 || playerChoice >= 3) {
System.out.println("That wasn't an option");
computerWins++;
gameCount++;
//The game goes on, and the winners are added up!
} else if (playerChoice == 0 && computerChoice == 1) {
computerWins++;
gameCount++;
System.out.println("Rock v Paper! Computer Wins!\n" +
"Player has won " + playerWins + " times and the computer " +
"has won " + computerWins + " times");
} else if (playerChoice == 1 && computerChoice == 0) {
playerWins++;
gameCount++;
System.out.println("Paper v Rock! Player Wins!\n" +
"Player has won " + playerWins + " times and the computer " +
"has won " + computerWins + " times");
} else if (playerChoice == 1 && computerChoice == 2) {
computerWins++;
gameCount++;
System.out.println("Paper v Scissors! Computer Wins!\n" +
"Player has won " + playerWins + " times and the computer " +
"has won " + computerWins + " times");
} else if (playerChoice == 2 && computerChoice == 1) {
playerWins++;
gameCount++;
System.out.println("Scissors v Paper! Player Wins!\n" +
"Player has won " + playerWins + " times and the computer " +
"has won " + computerWins + " times");
} else if (playerChoice == 2 && computerChoice == 0) {
computerWins++;
gameCount++;
System.out.println("Scissors v Rock! Computer Wins!\n" +
"Player has won " + playerWins + " times and the computer " +
"has won " + computerWins + " times");
} else if (playerChoice == 0 && computerChoice == 2) {
playerWins++;
gameCount++;
System.out.println("Rock v Scissors! Player Wins!\n" +
"Player has won " + playerWins + " times and the computer " +
"has won " + computerWins + " times");
} else if (playerChoice == 0 && computerChoice == 0) {
gameCount++;
System.out.println("Rock v Rock! Tie!\n" +
"Player has won " + playerWins + " times and the computer " +
"has won " + computerWins + " times");
} else if (playerChoice == 1 && computerChoice == 1) {
gameCount++;
System.out.println("Paper v Paper! Tie!\n" +
"Player has won " + playerWins + " times and the computer " +
"has won " + computerWins + " times");
} else if (playerChoice == 2 && computerChoice == 2) {
gameCount++;
System.out.println("Paper v Paper! Tie!\n" +
"Player has won " + playerWins + " times and the computer " +
"has won " + computerWins + " times");
}
//Check if game count reaches max games then chooses a winner
if (gameCount == 3 && computerWins > playerWins) {
System.out.println("The Computer Wins!");
} else if (gameCount == 3 && computerWins < playerWins) {
System.out.println("The Player Wins!");
} else if (gameCount == 3 && computerWins == playerWins) {
System.out.println("The game is a tie!");
}
}
}
So instead of playerChoice = userInput.nextInt(); try this:
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
try {
playerChoice = Integer.parseInt(input);
} catch (NumberFormatException e) {
if (input.equalsIgnoreCase("rock")) {
playerChoice = rock;
} else if (input.equalsIgnoreCase("paper")) {
playerChoice = paper;
} else if (input.equalsIgnoreCase("scissors")) {
playerChoice = scissors;
} else {
// if input is invalid
playerChoice = -1;
}
}
Since you're using userInput.nextInt() and playerChoice is an int and can only hold ints, you need to parse your user's input. In this case, Integer.parseInt(input) will try to find an int in the user input. If it can't it will return an exception; that's why there's a try-catch block. If it isn't an int, it will look for each string and assign the associated int value to playerChoice or -1 if the input is invalid. Then the rest of your code should be able to appropriately handle the playerChoice after that.

JAVA, How to restart my program from the start?

I am new to Java and I am doing some exercises, I created an if statement and else if so that when the user clicks 2 it will start the program from the start.
The problem is at the else if (yesNo == 2), I don't know what kind of code should I write there to start the program from the start. Can anybody help me? thank you.
if (option == 1) {
System.out.println("1: DAF");
System.out.println("2: Mercedes-benz");
model = in.nextInt();
if (model == 1) {
System.out.println("Model: " + mixer2.getModel());
System.out.println("Age: " + mixer2.getAge());
System.out.println("Cost: " + mixer2.getCost());
System.out.println("Capacity: " + mixer2.getCapacity() + " squares meters");
System.out.println("For how long do you want the vehicle to hire?, maximum is 12 months and every month cost 4000");
hireVehicle = in.nextInt();
cost = 4000 * hireVehicle;
System.out.println("The total cost is " + cost + " Do you want to proceed?");
System.out.println("1: yes");
System.out.println("2: no");
yesNo = in.nextInt();
if (yesNo == 1) {
System.out.println("Now, please enter your first name to complete the contract");
String name = in.next();
System.out.println("CUSTOMER CONTRACT");
System.out.println("Customer name: " + name);
System.out.println("Duration: " + hireVehicle + " months");
System.out.println("Date: " + date.date1());
}
else if (yesNo == 2){
}
You could use a loop like this one :
boolean repeat = True;
while (repeat)
{
if (yesNo ==1)
repeat = False;
else if (yesNo == 2)
repeat = True;
}
It might be easier with a do while loop, but i heard they're dirty

Better Algorithm? Better Array?

This is my code:
/* Name: Steven Royster
* Date: Jan. 15, 2015
* Rock, Paper, Scissors Program
* This program simulates a game of rock, paper, scissors with the user until someone has one a total of five times.
*/
import java.util.Random;
import java.util.Scanner;
public class RPS {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Let's play rock, paper, scissors! First to five wins!");
String[] choice = { "zero" , "rock" , "paper" , "scissors" };
Random rander = new Random();
Scanner input = new Scanner(System.in);
int userScore = 0, compScore = 0,
userChoice, compChoice;
while (compScore < 5 && userScore < 5)
{
compChoice = rander.nextInt(3) + 1;
System.out.println("\nEnter: 1 for ROCK | 2 for PAPER | 3 for SCISSORS.");
userChoice = input.nextInt();
if (compChoice == userChoice) // tie
{
System.out.println("I chose " + choice[compChoice] + " too, so we tied!");
}
else if ( ( compChoice == 1 && userChoice == 3 ) //computer wins
|| ( compChoice == 2 && userChoice == 1 )
|| ( compChoice == 3 && userChoice == 2) )
{
System.out.println("I win! I chose " + choice[compChoice] + ". " +
choice[compChoice] + " beats " + choice[userChoice] + "." );
compScore += 1;
}
else //human wins
{
System.out.println("You win! I chose " + choice[compChoice] + ". " +
choice[userChoice] + " beats " + choice[compChoice] + ".");
userScore += 1;
}
}//end while
if (userScore == 5)
{
System.out.println("\nCongrats! You're the winner! You got "
+ userScore + " points. I only got " + compScore + " points." );
}
}//end main
}//end class
Is there a better algorithm I can implement rather than using the three separate conditions within my else-if statement? Also, instead of having the 'zero' string in my array, how could I check through my array using only numbers 1, 2, and 3?
Just use
String[] choice = { "rock" , "paper" , "scissors" };
Then instead of choice[userChoice] you can do choice[userChoice - 1].
You don't need to write
if ( ( compChoice == 1 && userChoice == 3 )
|| ( compChoice == 2 && userChoice == 1 )
|| ( compChoice == 3 && userChoice == 2) )
because it is the same as
if (compChoice == 1 + (userChoice % 3))

Converting number outputs and inputs into words

i had a quick question, so i finished up writing my program which is a simple Rock, Paper Scissors game but at the moment it only displays 0,1,2 which 0 is scissors, 1 is rock, and 2 is paper. The problem im having is that im not quite sure how to give the users input as well as what the computer outputs go from displaying numbers to displaying scissors, rock, paper.
import java.util.Scanner;
import java.lang.Math;
public class Lab3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Hello user! lets play ");
System.out.println("Rock, Paper, Scissors.");
System.out.println();
System.out.print("Type in 0 for Scissors, 1 for Rock, or 2 for Paper ");
int userInput = in.nextInt();
int opponentsHand = (int)(Math.random()*3);
if (userInput == opponentsHand)
{
System.out.print("Darth Vader has played " + opponentsHand);
System.out.println(" Despite your efforts of playing " + userInput + ", this battle has ended in a draw!");
}
if (userInput < opponentsHand && opponentsHand != 2)
{
System.out.print("Darth vader has played "+ opponentsHand);
System.out.println(", You played " + userInput + "You have Lost");
}
else if (userInput < opponentsHand && opponentsHand == 2)
{
System.out.print("Darth Vader has played " + opponentsHand);
System.out.println(" You played " + userInput + " You have won");
}
if (userInput > opponentsHand && opponentsHand != 0)
{
System.out.print("Darth Vader has played " + opponentsHand);
System.out.println(" You have played " + userInput + " You have won");
}
else if (userInput > opponentsHand && opponentsHand == 0)
{
System.out.print("Darth Vader has played " + opponentsHand);
System.out.println(" You have played " + userInput + " You have lost");
}
}
}
thank you
One way is to simply use an array to store the names of the hands:
String[] hands = {"scissors", "rock", "paper"};
When you print, you do the following:
System.out.print("Darth Vader has played " + hands[opponentsHand]);

Categories