I have an assignment to make a rock paper scissors game that will allow the user to input "R, P, S, or Q to quit." If user enters Q to quit, it must display the wins and losses and in percentage format. I tried dabbling with inheritance, but I made this in case I don't find a more efficient, probably more OOP way to go about this.
My question is: Is there a quicker, more efficient way to code this? OOP seems like it could work, but it doesn't have to be.
// main method
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// variables
double wins = 0;
double losses = 0;
double draws = 0;
double games = 0;
Integer answer1 = null;
boolean playing = true;
// start of game
while (playing)
{
// main menu
System.out.println("Input R, P, S, or Q(to quit).");
String answer = scan.next();
// player's move
answer = answer.toLowerCase();
// computer's move
Random random = new Random();
Integer choice = random.nextInt(3); // n-1
String comp = choice.toString();
System.out.println(comp);
// converts player's move from str to int
switch (answer)
{
case "r":
answer1 = 0;
break;
case "p":
answer1 = 1;
break;
case "s":
answer1 = 2;
break;
case "q":
System.out.println("User exit.");
double winP = wins/games*100;
double loseP = losses/games*100;
double drawP = draws/games*100;
System.out.println("Wins: " + wins);
System.out.printf("%.2f", winP);
System.out.println(" Percent");
System.out.println("Losses: " + losses);
System.out.printf("%.2f", loseP);
System.out.println(" Percent");
System.out.println("Draws: " + draws);
System.out.printf("%.2f", drawP);
System.out.println(" Percent");
answer1 = null;
playing = false;
break;
}
// checks for conditions
// draw
if (playing == true)
{
if (answer1 == choice)
{
System.out.println("Draw");
draws++;
games++;
}
// losses
if (answer1 == 0 && choice == 1)
{
System.out.println("YOU LOSE! :D");
losses++;
games++;
}
if (answer1 == 1 && choice == 2)
{
System.out.println("YOU LOSE! :D");
losses++;
games++;
}
if (answer1 == 2 && choice == 0)
{
System.out.println("YOU LOSE! :D");
losses++;
games++;
}
// wins
if (answer1 == 0 && choice == 2)
{
System.out.println("you win... :D");
wins++;
games++;
}
if (answer1 == 1 && choice == 0)
{
System.out.println("you win... :D");
wins++;
games++;
}
if (answer1 == 2 && choice == 1)
{
System.out.println("you win... :D");
wins++;
games++;
}
}
}
}
Here's a version of rock, paper, scissors that I did. I have a GameModel class that holds the values for a rock, paper, scissors game, and a RockPaperScissors class that provides the user interface.
Here's an example of the user interface:
Rock, Paper, Scissors; Enter r, p, s, or q to quit: s
We chose the same item. Let's try again.
Rock, Paper, Scissors; Enter r, p, s, or q to quit: s
You chose Scissors, the computer chose Rock. The computer wins.
Rock, Paper, Scissors; Enter r, p, s, or q to quit: r
You chose Rock, the computer chose Paper. The computer wins.
Rock, Paper, Scissors; Enter r, p, s, or q to quit: s
We chose the same item. Let's try again.
Rock, Paper, Scissors; Enter r, p, s, or q to quit: s
You chose Scissors, the computer chose Rock. The computer wins.
Rock, Paper, Scissors; Enter r, p, s, or q to quit: q
The final score: Player 0, Computer 3, ties 2.
And here's the code:
package com.ggl.testing;
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors implements Runnable {
private GameModel gameModel;
private Random random;
public static void main(String[] args) {
new RockPaperScissors().run();
}
public RockPaperScissors() {
this.random = new Random();
this.gameModel = new GameModel();
}
#Override
public void run() {
Scanner scanner = new Scanner(System.in);
char inputChar = getUserChoice(scanner);
while (inputChar != gameModel.getQuitCharacter()) {
char computerChar = generateComputerChoice();
System.out.println(gameModel.calculateGameResult(inputChar,
computerChar));
inputChar = getUserChoice(scanner);
}
System.out.println(gameModel.displayFinalScore());
scanner.close();
}
private char getUserChoice(Scanner scanner) {
char inputChar = ' ';
while (gameModel.getCharacterIndex(inputChar) < 0) {
System.out.print(gameModel.generatePrompt());
String input = scanner.nextLine().toLowerCase();
inputChar = input.charAt(0);
}
return inputChar;
}
private char generateComputerChoice() {
int index = random.nextInt(gameModel.getChoicesLength() - 1);
return gameModel.getChoiceCharacter(index);
}
public class GameModel {
private final String[] CHOICES = { "Rock", "Paper", "Scissors", "Quit" };
private int playerScore;
private int computerScore;
private int tieScore;
public GameModel() {
this.playerScore = 0;
this.computerScore = 0;
this.tieScore = 0;
}
public String getChoice(int index) {
return CHOICES[index];
}
public char getChoiceCharacter(int index) {
return CHOICES[index].toLowerCase().charAt(0);
}
public int getChoicesLength() {
return CHOICES.length;
}
public char getQuitCharacter() {
return getChoiceCharacter(getChoicesLength() - 1);
}
public int getPlayerScore() {
return playerScore;
}
public int getComputerScore() {
return computerScore;
}
public int getTieScore() {
return tieScore;
}
public String generatePrompt() {
StringBuilder builder = new StringBuilder();
builder.append(CHOICES[0]);
builder.append(", ");
builder.append(CHOICES[1]);
builder.append(", ");
builder.append(CHOICES[2]);
builder.append("; Enter ");
builder.append(getChoiceCharacter(0));
builder.append(", ");
builder.append(getChoiceCharacter(1));
builder.append(", ");
builder.append(getChoiceCharacter(2));
builder.append(", or ");
builder.append(getChoiceCharacter(3));
builder.append(" to ");
builder.append(CHOICES[3].toLowerCase());
builder.append(": ");
return builder.toString();
}
public String calculateGameResult(char inputChar, char computerChar) {
if (inputChar == computerChar) {
tieScore++;
return "We chose the same item. Let's try again.\n";
} else {
int inputIndex = getCharacterIndex(inputChar);
int computerIndex = getCharacterIndex(computerChar);
String s = "You chose " + CHOICES[inputIndex]
+ ", the computer chose " + CHOICES[computerIndex]
+ ". ";
int testIndex = (inputIndex + 1) % (CHOICES.length - 1);
if (testIndex == computerIndex) {
computerScore++;
return s + "The computer wins.\n";
} else {
playerScore++;
return s + "You win.\n";
}
}
}
private int getCharacterIndex(char c) {
for (int index = 0; index < CHOICES.length; index++) {
if (c == getChoiceCharacter(index)) {
return index;
}
}
return -1;
}
public String displayFinalScore() {
StringBuilder builder = new StringBuilder();
builder.append("\nThe final score: Player ");
builder.append(playerScore);
builder.append(", Computer ");
builder.append(computerScore);
builder.append(", ties ");
builder.append(tieScore);
builder.append(".");
return builder.toString();
}
}
}
Related
Hey guys having some trouble with a multi part question. I'm trying to get a game of rock paper scissors done, when i try to test the code using the playRound method I have to input my choice over and over again and then it just prints out draw, you are the winner and the computer is the winner over and over, can anyone tell me where im going wrong ?
import java.util.Scanner;
import java.util.Random;
/**
* A class that will play a game of rock paper scissors.
*
* #author (your name)
* #version (a version number or a date)
*/
public class RockPaperScissors
{
private Scanner reader;
private int yourScore;
private int computerScore;
private Random ran = new Random();
public RockPaperScissors()
{
reader = new Scanner(System.in);
yourScore = 0;
computerScore=0;
Random ran = new Random();
}
public void printPrompt()
{
System.out.println("Enter your choice, paper, rock or scissors >");
String userChoice = userChoice();
System.out.println();
System.out.println();
System.out.println("Enter your choice, paper, rock or scissors >"+ userChoice);
}
public final String userChoice()
{
String userChoice= reader.next();
return userChoice;
}
public String computerChoice()
{
String compMove = ("");
int cpuChoice = ran.nextInt(3);
switch(cpuChoice)
{
case 0:
{
compMove = ("rock");
break;
}
case 1:
{
compMove = ("paper");
break;
}
case 2:
{
compMove = ("scissors");
break;
}
}
return (compMove);
}
public String findWinner(String yourChoice, String computerChoice)
{
yourChoice = userChoice();
computerChoice = computerChoice();
String Winner= null;
if (yourChoice.equals(computerChoice))
{
Winner = ("draw");
}
if (yourChoice.equals("rock"))
{
if (computerChoice.equals("paper"))
{
computerScore++;
Winner = ("computer");
}
else if (computerChoice == "scissors")
{
yourScore++;
Winner = ("you");
}
}
if (yourChoice.equals("paper"))
{
if (computerChoice.equals("scissors"))
{
computerScore++;
Winner = ("computer");
}
else if (computerChoice.equals("rock"))
{
yourScore++;
Winner = ("you");
}
}
if (yourChoice.equals("scissors"))
{
if (computerChoice.equals("rock"))
{
computerScore ++;
Winner = ("computer");
}
else if (computerChoice.equals("paper"))
{
yourScore++;
Winner = ("you");
}
}
if (!yourChoice.equals("rock||paper||scissors"))
{
computerScore++;
Winner = ("computer");
}
return Winner;
}
public void playRound()
{
printPrompt();
String computerChoice=computerChoice();
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
String findWinner = findWinner(computerChoice,userChoice);
{
if (findWinner.equals("draw"));
System.out.println("This game is a draw");
if (findWinner.equals("you"));
System.out.println("You are the winner");
if (findWinner.equals("computer"));
System.out.println("The computer is the winner");
}
System.out.println("You have " + yourScore + "and the computer has "+ computerScore);
}
}
The semicolon at the end of your if statements means that the if statement is COMPLETE. The lines immediately following your if statements are then stand-alone, they do not "belong" to the if statements...which is why they always run.
Change:
if (findWinner.equals("draw"));
System.out.println("This game is a draw");
To:
if (findWinner.equals("draw"))
System.out.println("This game is a draw");
Or even better:
if (findWinner.equals("draw")) {
System.out.println("This game is a draw");
}
Any advice on how i can get my initial choice to be saved so I don't
have to keep typing it in ?
In findWinner(), you're calling userChoice() and computerChoirce() AGAIN. At that point, the values are already in the parameters that were passed in, so you don't need those. Comment them out or remove them:
public String findWinner(String yourChoice, String computerChoice)
{
// You don't need these two lines:
//yourChoice = userChoice();
//computerChoice = computerChoice();
// ... other existing code ...
}
Then, in playRound(), you are calling both printPrompt() and userChoice(), which each have their own input mechanism:
printPrompt();
String computerChoice=computerChoice();
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
I'd get rid of printPrompt() and just do:
// printPrompt();
String computerChoice=computerChoice();
System.out.print("Enter your choice, paper, rock or scissors >");
String userChoice=userChoice();
System.out.println("You have chosen " + userChoice + " and the computer has chosen " + computerChoice);
You have some broken logic in findWinner(). This does not do what you think it does:
if (!yourChoice.equals("rock||paper||scissors"))
{
computerScore++;
Winner = ("computer");
}
I think what you were trying to do is make the computer win if the user did not type in "rock", "paper", or "scissors"? If so, change your if statements to else if statements and add a final else block:
public String findWinner(String yourChoice, String computerChoice)
{
String Winner = "";
if (yourChoice.equals(computerChoice))
{
Winner = "draw";
}
else if (yourChoice.equals("rock"))
{
if (computerChoice.equals("paper"))
{
computerScore++;
Winner = "computer";
}
else if (computerChoice.equals("scissors"))
{
yourScore++;
Winner = "you";
}
}
else if (yourChoice.equals("paper"))
{
if (computerChoice.equals("scissors"))
{
computerScore++;
Winner = "computer";
}
else if (computerChoice.equals("rock"))
{
yourScore++;
Winner = "you";
}
}
else if (yourChoice.equals("scissors"))
{
if (computerChoice.equals("rock"))
{
computerScore ++;
Winner = "computer";
}
else if (computerChoice.equals("paper"))
{
yourScore++;
Winner = "you";
}
}
else // user did not type "rock", "paper", or "scissors"!
{
computerScore++;
Winner = ("computer");
}
return Winner;
}
Lastly, MAJOR bug, you SWAPPED the order of your parameters when you called findWinner().
Change:
String findWinner = findWinner(computerChoice, userChoice);
To:
String findWinner = findWinner(userChoice, computerChoice);
Hope that helps!
I am a student of 2 months so bear with me here.
I am trying to show my friend a Rock, Paper, Scissors game in action. I've successfully created RockPaperScissors.exe using Launch4j.
Now when I click the game's executable file I get the console to open. But when my friend tries to do so, he gets the console with no words in it, if he tries to type it closes.
Is it possible to have an executable file force the console up? Do I need to change some part of my code in order to have that happen?
Code is below in case I need to add something to make this work.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
/***** CONSTANT SECTION *****/
public static void main(String[] args)
{
/***** DECLARATION SECTION *****/
Scanner keyboard;
Random rndGen;
char computerChoice;
int playerScore, compScore;
int winner, compInt;
String name;
String userChoice;
/***** INITIALIZATION SECTION *****/
keyboard = new Scanner(System.in);
rndGen = new Random();
computerChoice = ' ';
winner = -1;
compInt = -1;
playerScore = 0;
compScore = 0;
/***** INTRO SECTION *****/
System.out.print("What is your name? ");
name = keyboard.next();
System.out.println("\nHi " + name + ".");
System.out.println("\nLet's play Rock, Paper, Scissors!");
System.out.println("Best out of 3 wins.");
/***** INPUT SECTION *****/
while (playerScore < 2 && compScore < 2)
{
System.out.print("\nEnter your choice. Type R for rock, P for paper, or S for scissors: ");
//takes a char entry and changes it into a string, upper cases the entry, and then take the first letter of the string
userChoice = keyboard.next();
userChoice = userChoice.toUpperCase();
while (!(userChoice.equals("R") || userChoice.equals("P") || userChoice.equals("S")))
{
System.out.println("Invalid entry.");
System.out.println("");
System.out.print("Enter your choice. Type R for rock, P for paper, or S for scissors: ");
userChoice = keyboard.next();
userChoice = userChoice.toUpperCase();
}
/***** PROCESSING SECTION *****/
compInt = rndGen.nextInt(3);
if (compInt == 0)
{
computerChoice = 'R';
}
else if (compInt == 1)
{
computerChoice = 'P';
}
else
{
computerChoice = 'S';
}
winner = RockPaperScissors.decideWinner(userChoice,computerChoice);
/***** OUTPUT SECTION *****/
System.out.printf(name + " chose %s%nComputer chose %c%n",userChoice,computerChoice);
switch(winner)
{
case 0: System.out.println("It's a tie!");
break;
case 1: System.out.println(name + " wins!");
playerScore = playerScore + 1;
break;
case 2: System.out.println("Computer won!");
compScore = compScore + 1;
break;
default: System.out.println("Invalid choice. Try again");
break;
}
System.out.println(name + ": " + playerScore + ", Computer: " + compScore);
}
if (playerScore > compScore)
{
System.out.println("\n" + name + " is the winner!!!");
}
else
{
System.out.println("\nSorry, the computer wins this time.");
}
keyboard.close();
System.out.println("Thanks for playing!");
}
/***** STATIC METHODS *****/
//Given two characters (R, P or S) determines //winner user rock paper scissors rules. Error check
//done in main
public static int decideWinner(String p1,char p2)
{
String combo;
combo = String.format("%s%c",p1,p2);
if ((combo.equals("RS")) || (combo.equals("PR")) || (combo.equals("SP")))
{
return 1;
}
else if ((combo.equals("RP")) || (combo.equals("PS")) || (combo.equals("SR")))
{
return 2;
}
else if ((combo.equals("PP")) || (combo.equals("SS")) || (combo.equals("RR")))
{
return 0;
}
else
{
return -1;
}
}
}
I'm trying to make a simple BlackJack game driven by character input and I'm having a lot of problems in the later part it.
I commented the part that's giving me troubles, the rest doesn't seem to have errors and I did unit test it.
So, what did I do? I created a class that holds the cards drawn and manages them, table, player and dealer are both instances of table.
A table has max 5 cards(for simplicity), every card object comes from the Card class that has a method to add data to the card object.
The main class drives the program and the decisions are made with a character input from the keyboard, I get problems at that point.
import java.io.IOException;
class Table{
Card[] hand = new Card[5];
int counter = 1;
Table() {
for ( int i=0; i<hand.length; i++) {
hand[i]=new Card();
}
hand[0].GetCard();
}
void ReadCards(){
for(int i= 0;i<counter;i++ ) {
System.out.println("The card "+(i+1)+" is " + hand[i].name + " "+ hand[i].seed + "." );
}
}
void DrawCards() {
hand[counter].GetCard();
counter++;
}
boolean isOut() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
if(sum >21) {
return true;
}
}
return false;
}
int TheSum() {
int sum = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
return sum;
}
boolean isWIN(Table p2) {
int sum = 0;
int sump2 = 0;
for(int i= 0;i<counter;i++ ) {
sum += hand[i].value;
}
for(int i= 0;i<p2.counter;i++ ) {
sump2 += p2.hand[i].value;
}
if (sum>sump2) {
return true;
}
else return false;
}
class Card {
public int value = 0;
public String name = "";
public String seed = "";
void GetCard(){
int positive = 0;
do {
positive = (int) (Math.random()*100) % 10;
}while(positive == 0 );
value = positive;
if(value<10) {
name = String.valueOf(value);
}
else {
positive = 0;
do {
positive = (int) (Math.random()*100) % 3;
}while(positive == 0 );
switch(positive) {
case 1:
name = "J";
break;
case 2:
name = "Q";
break;
case 3:
name ="K";
break;
}
}
positive = 0;
do {
positive = (int) (Math.random()*100) % 4;
}while(positive == 0 );
switch(positive) {
case 1:
seed = "CLUB";
break;
case 2:
seed = "DIAMOND";
break;
case 3:
seed ="SPADE";
break;
case 4:
seed ="HEART";
break;
}
}
}
}
public class BlackJack {
public static void main(String args[])throws IOException {
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char)System.in.read();
}while(flag != 'y' );
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
/*
flag = (char)System.in.read();
while(flag != 'n' ) {
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
flag = (char)System.in.read();
}
System.out.println("The dealer will draw");
while(dealer.TheSum()<18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
*/
System.out.println("WHO WON?");
if (player.isWIN(dealer)){
System.out.println("YOU WIN");
}
else System.out.println("YOU LOSE");
}
}
And yes, I'm not used to java.
Console screenshot of the output here!
Here is an example of fixing your looping issues, however there may be some issue with the game logic, which is out of the scope of this question.
public static void main(String args[]) throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Welcome to the BlackJack's table! Press y to start! ");
char flag;
do {
flag = (char) s.nextLine().charAt(0);
} while (flag != 'y');
Table dealer = new Table();
Table player = new Table();
System.out.println("DEALER");
dealer.ReadCards();
System.out.println("PLAYER");
player.ReadCards();
flag = ' ';
System.out.println("Do you want to draw a card? I'll draw until you'll press n");
while (true) {
flag = s.nextLine().charAt(0);
if (flag == 'n') {
break;
}
player.DrawCards();
player.ReadCards();
if (player.isOut()) {
System.out.println("YOU LOSE");
System.exit(0);
}
System.out.println("The dealer will draw");
while (dealer.TheSum() < 18) {
dealer.DrawCards();
dealer.ReadCards();
if (dealer.isOut()) {
System.out.println("YOU WIN");
System.exit(0);
}
}
System.out.println(String.format("The dealer has finished drawing. Dealers score %d. Your score %d", dealer.TheSum(), player.TheSum()));
}
System.out.println("WHO WON?");
if (player.isWIN(dealer)) {
System.out.println("YOU WIN");
} else {
System.out.println("YOU LOSE");
}
}
Output:
Welcome to the BlackJack's table! Press y to start!
y
DEALER
The card 1 is 8 CLUB.
PLAYER
The card 1 is 2 SPADE.
Do you want to draw a card? I'll draw until you'll press n
n
WHO WON?
YOU LOSE
So my task today is to make a rock paper scissors game using methods. My first problem with my code is that I need it to ask the user if they want to play again or not. (y or n) Also, I need to implement scoring, 1 point if user wins, -1 if they lose, and for each time they play again add that score to total score. Any ideas on how to implement this? or what I need to change to my code. Also I am a rookie so sorry for the ugly formatting and feel free to critic every little detail, ill soak up all the information I can.
public static void main(String[] args){
boolean tie = true;
do{
String computer = computerChoice();
String user = userChoice();
tie = (computer.compareTo(user) == 0);
determineWinner(computer, user);
}while(tie);
}
public static String computerChoice( ){
Random rand = new Random();
int cinput = rand.nextInt(3)+ 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static String userChoice(){
Scanner sc = new Scanner (System.in);
String user = "default";
do{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
}
while (isValidChoice (user) == false);
return user;
}
public static boolean isValidChoice(String choice){
boolean status;
if (choice.compareTo("Rock")== 0)
status = true;
else if (choice.compareTo("Paper")== 0)
status = true;
else if (choice.compareTo("Scissors")== 0)
status = true;
else{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static boolean determineWinner(String computer, String user){
System.out.println (" Computer Choice: " + computer);
System.out.println ("Your Choice : " + user);
if (computer.compareTo( "Rock" ) == 0 && user.compareTo ("Scissors") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Scissors")== 0 && user.compareTo("Paper") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Rock") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Rock") == 0 && user.compareTo("Paper") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Scissors") == 0 && user.compareTo("Rock") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Scissors") == 0)
System.out.println (" You win!!");
else if (computer.compareTo(user) == 0 ){
System.out.println(" Tie! the game must be played again.");
return false;
}
return true;
}
}
a output that my professor gave us as an example is:
Choose your weapon!
1. Paper
2. Scissors
3. Rock
5
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose rock!
I have been vanquished!
We have matched wits 1 times, and your score is 1
Do you want to play again (y or n)? y
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose paper!
We are equally matched. You are a worthy adversary.
We have matched wits 2 times, and your score is 1
Do you want to play again (y or n)? n
Here is the finished code. I added two functions, one to call the actual game and one to check if the player wanted to play again. Also, there is the concluding sentence in the end
import java.util.Random;
import java.util.Scanner;
public class RPC
{
public static Scanner sc = new Scanner(System.in);
public static int score = 0;
public static int gameCount = 0;
public static void main(String[] args)
{
play();
while (playAgain())
{
play();
}
}
public static void play()
{
String computer = computerChoice();
String user = userChoice();
determineWinner(computer, user);
}
public static String computerChoice()
{
Random rand = new Random();
int cinput = rand.nextInt(3) + 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static boolean playAgain()
{
System.out.println("Play again?(y/n)");
String input = sc.nextLine();
if (input.toLowerCase().equals("y"))
{
return true;
} else if (input.toLowerCase().equals("n"))
{
return false;
} else
{
System.out.println("Invalid Input");
return playAgain();
}
}
public static String userChoice()
{
String user = "default";
do
{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
} while (!isValidChoice(user));
return user;
}
public static boolean isValidChoice(String choice)
{
boolean status;
if (choice.equals("Rock"))
status = true;
else if (choice.equals("Paper"))
status = true;
else if (choice.equals("Scissors"))
status = true;
else
{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static void determineWinner(String computer, String user)
{
gameCount++;
System.out.println(" Computer Choice: " + computer);
System.out.println("Your Choice : " + user);
if (computer.equals("Rock") && user.equals("Scissors"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Scissors") && user.equals("Paper"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Paper") && user.equals("Rock"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Rock") && user.equals("Paper"))
{
score++;
System.out.println(" You win!!");
}
if (computer.equals("Scissors") && user.equals("Rock"))
{
score++;
System.out.println(" You win!!");
}
if (computer.equals("Paper") && user.equals("Scissors"))
{
score++;
System.out.println(" You win!!");
} else if (computer.equals(user))
{
System.out.println(" Tie! the game must be played again.");
}
System.out.println("We have matched wits" + gameCount + "times, and your score is" + score);
return;
}
}
Hi I am making a simple rock, paper, scissors game and was having some trouble getting my compare method to get executed. The game prompts the user for input, and then using the computersTurn method to allow the computer to randomly select rock paper or scissors. When I try and pass both these values into my compare method, it doesn't seem to work. Any suggestions would be awesome!
import java.util.Scanner;
public class sillyGame {
public static void compare (String choice1, String choice2)
{
if (choice1.equals(choice2))
{
System.out.println("The result is a tie!");
}
if (choice1.contains("rock"))
{
if (choice2.contains("scissors"))
{
System.out.println("rock wins");
}
if (choice2.contains("paper"))
{
System.out.println("paper wins");
}
}
if (choice1.contains("scissors"))
{
if (choice2.contains("rock"))
{
System.out.println("rock wins");
}
if (choice2.contains("paper"))
{
System.out.println("scissors wins");
}
}
if (choice1.contains("paper"))
{
if (choice2.contains("rock"))
{
System.out.println("paper wins");
}
if (choice2.contains("scissors"))
{
System.out.println("scissors wins");
}
}
}
public static String computersTurn(String compFinalChoice, double randomNum){
randomNum = Math.random();
if (randomNum < 0.34)
{
compFinalChoice = "rock";
}
else if(randomNum <= 0.67)
{
compFinalChoice = "paper";
}
else
{
compFinalChoice = "scissors";
}
System.out.println("The computer chooses " + compFinalChoice);
return compFinalChoice;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Do you choose rock, paper or scissors?");
String userChoice = scan.nextLine();
String computerDec = " ";
double rand = 0.0;
computersTurn(computerDec, rand);
compare(userChoice, computerDec);
}
Your computersTurn method doesn't need any parameters. You're just passing it " " and 0.0.
Try changing it to this method:
public static String computersTurn() {
// declare them here
double randomNum = Math.random();
String compFinalChoice = "";
if (randomNum < 0.34) {
compFinalChoice = "rock";
}
else if(randomNum <= 0.67) {
compFinalChoice = "paper";
}
else {
compFinalChoice = "scissors";
}
System.out.println("The computer chooses " + compFinalChoice);
return compFinalChoice;
}
And then in your main method, make sure when you call the computersTurn() method, you assign it to a String. Calling it does nothing for you; you need to keep the return value:
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Do you choose rock, paper or scissors?");
String userChoice = scan.nextLine();
String computerDec = computersTurn(); // assign it here
compare(userChoice, computerDec);
}
You cannot update a String (or a double) from a caller so I think you should re-factor computersTurn like so
public static String computersTurn() {
String choice = "scissors";
double randomNum = Math.random();
if (randomNum < 0.34) {
choice = "rock";
} else if (randomNum <= 0.67) {
choice = "paper";
}
System.out.println("The computer chooses "
+ choice);
return choice;
}
Then you can do something like this in main
String computerDec = computersTurn();
or
String userChoice = scan.nextLine();
compare(userChoice, computersTurn());