So im making everyone's fun game "Rock, Paper, Scissors" I got everything working, except having the while loop repeat 3 time before stopping. Well it does repeat 3 times and stops, but the 2nd and 3rd repeat the variables don't change. Take a look at the code and tell me what I'm doing wrong.
**UPDATE: Now that I have everything working how do I get this "Q" string to terminate the loop?
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
/**
* (Insert a brief description that describes the purpose of this method)
*
* #param args
*/
public static void main(String[] args)
{
int compint;
String usermove = "";
String compmove = "";
String winner = "";
int count = 0;
Scanner in = new Scanner(System.in);
Random gen = new Random();
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
int input = in.nextInt();
while (count < 3)
{
compint = gen.nextInt(3) + 1;
if (input == 1)
{
usermove = "Rock";
}
else if (input == 2)
{
usermove = "Paper";
}
else if (input == 3)
{
usermove = "Scissors";
}
if (compint == 1)
{
compmove = "Rock";
}
else if (compint == 2)
{
compmove = "Paper";
}
else if (compint == 3)
{
compmove = "Scissors";
}
if (compint == input)
{
winner = "TIE";
}
else if (compint == 1 && input == 3)
{
winner = "COMPUTER";
}
else if (compint == 2 && input == 1)
{
winner = "COMPUTER";
}
else if (compint == 3 && input == 2)
{
winner = "COMPUTER";
}
else
{
winner = "USER";
}
System.out.print("Computer: " + compmove + " | ");
System.out.print("You: " + usermove + " | ");
System.out.println("Winner: " + winner);
System.out.println();
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input = in.nextInt();
count++;
}
}
}
Output:
Enter Rock(1), Paper(2), Scissors(3) {Q to quit]:
1
Computer: Scissors | You: Rock | Winner: USER
Enter Rock(1), Paper(2), Scissors(3) {Q to quit]:
2
Computer: Rock | You: Paper | Winner: USER
Enter Rock(1), Paper(2), Scissors(3) {Q to quit]:
Q
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at RockPaperScissors.main(RockPaperScissors.java:102)
The logic that actually does anything with the input – all those if statements – is outside of the loop. With each iteration through the look, none of that logic is not actually executed. It all just happens first. Try this instead:
for (int count=0; count < 3; count++)
{
int input = in.nextInt();
int compint = gen.nextInt(3) + 1;
// all the if statements and printing here
}
**UPDATE: Now that I have everything working how do I get this "Q" string to terminate the loop?
You're getting an InputMismatchException when typing Q but the code calls Scanner#nextInt(). The docs are pretty clear on what the problem is:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
It's basically the Scanner's way of telling you "you asked for an int but the next token isn't one." You can add an additional check before the nextInt() calls, using Scanner#hasNextInt(), to verify that the next token actually is an int. If it's not an int, then you can plan on parsing it just as a string.
So instead of this:
input = in.nextInt();
Do something like this:
if (in.hasNextInt())
{
input = in.nextInt();
} else if (in.hasNext("Q")) {
// quit
}
seems you wanted to use do - while loop
it would work:
do{
compint = gen.nextInt(3) + 1;
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
int input = in.nextInt();
if (input == 1)
{
usermove = "Rock";
}
else if (input == 2)
{
usermove = "Paper";
}
else if (input == 3)
{
usermove = "Scissors";
}
if (compint == 1)
{
compmove = "Rock";
}
else if (compint == 2)
{
compmove = "Paper";
}
else if (compint == 3)
{
compmove = "Scissors";
}
if (compint == input)
{
winner = "TIE";
}
else if (compint == 1 && input == 3)
{
winner = "COMPUTER";
}
else if (compint == 2 && input == 1)
{
winner = "COMPUTER";
}
else if (compint == 3 && input == 2)
{
winner = "COMPUTER";
}
else
{
winner = "USER";
}
System.out.print("Computer: " + compmove + " | ");
System.out.print("You: " + usermove + " | ");
System.out.println("Winner: " + winner);
System.out.println("Enter Rock(1), Paper(2), Scissors(3) {Q to quit]: ");
input = in.nextInt();
count++;
}while (count < 3);
Related
I am trying to add an exit option to this code. Also, my results will not read correctly, and I am not sure what I am doing wrong. I've tried using a do while loop, but I can't seem to place it in the correct place.
//import Scanner Class
import java.util.Scanner;
import java.util.Random;
public class JavaMidterm {
public static void main(String[] args) {
String result = " ", symbola = " ", symbolb = " ";
Scanner s = new Scanner(System.in);
//prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
// read user choice
int choice=s.nextInt();
//Create random class object
Random random = new Random();
//Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if(choice == pick)
result = "It is a draw";
else {
if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick ==0)) || ((choice == 2) && (pick == 1)) )
result = "You won";
else
result = "You lose";
}
if(pick == 0)
symbola = "Scissor";
if(choice == 0)
symbolb = "Scissor";
//assigning symbols to the corresponding values
if(pick == 1)
symbolb = "Rock";
if(pick == 2)
symbola = "Paper";
if(choice == 2)
symbolb = "Paper";
System.out.println("The computer is" +
symbola + ". You are" + symbolb + ". " + result);
}
}
You can try my solution below. I have also included checking for invalid inputs. I also simplified the checking for your result.
//import Scanner Class
import java.util.Random;
import java.util.Scanner;
public class JavaMidterm {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Create random class object
Random random = new Random();
String[] choices = new String[] { "Scissor", "Rock", "Paper" };
int choice;
// prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
while (true) {
try {
String result = "";
// read user choice
choice = Integer.parseInt(s.nextLine());
if (choice < 0 || choice > 2) {
throw new Exception();
}
// Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if (choice == pick)
result = "It is a draw";
else if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick == 0))
|| ((choice == 2) && (pick == 1)))
result = "You won";
else
result = "You lose";
System.out.println("The computer is " + choices[pick] + ". You are " + choices[choice] + ". " + result);
System.out.print("Do you want to play again? Yes (0), No (1): ");
while (true) {
try {
// read user choice
choice = Integer.parseInt(s.nextLine());
if (choice < 0 || choice > 1) {
throw new Exception();
}
if (choice == 0)
System.out.print("Scissor (0), rock (1), paper (2): ");
break;
} catch (Exception e) {
System.out.println("Invalid input.");
System.out.print("Do you want to play again? Yes (0), No (1): ");
}
}
if (choice == 1) {
break;
}
} catch (Exception e) {
System.out.println("Invalid input.");
System.out.print("Scissor (0), rock (1), paper (2): ");
}
}
s.close();
}
}
I assume that you wish to end the game in case of a "win" and continue the game in case of "losing". Assuming that the code can be modified like below,
boolean isGoodToContinue = true;
while (isGoodToContinue) {
String result = " ", symbola = " ", symbolb = " ";
Scanner s = new Scanner(System.in);
// prompt user
System.out.print("Scissor (0), rock (1), paper (2): ");
// read user choice
int choice = s.nextInt();
// Create random class object
Random random = new Random();
// Generate a random number from 0, 1, 2
int pick = random.nextInt(3);
if (choice == pick)
result = "It is a draw";
else {
if (((choice == 0) && (pick == 2)) || ((choice == 1) && (pick == 0))
|| ((choice == 2) && (pick == 1))) {
result = "You won";
isGoodToContinue = false;
}
else {
result = "You lose";
isGoodToContinue = true;
}
}
I am currently working on this project that plays the high low dice game. I am stuck on how to use the returned char from getHighLow and the returned int from getBet and getRoll in determineWinnings. This is my first year learning Java currently, so any help would be appreciated. Thank you in advance for any help you can give!
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int currentPool = 100;
getBet(keyboard, currentPool);
getHighLow(keyboard);
getRoll();
>> determineWinnings(highLow, userBet, rollSum);
}
// Given a Scanner and a current maximum amount of money, prompt the user for
// an integer representing the number of dollars that they want to bet. This
// number must be between 0 and to maximum number of dollars. If the user enters
// a number that is out of bounds, display an error message and ask again.
// Return the bet to the calling program.
private static int getBet(Scanner inScanner, int currentPool) {
int userBet = -1;
while (userBet == -1) {
inScanner = new Scanner(System.in);
System.out.println("You have $" + currentPool);
System.out.println("Enter an amount to bet (0 to quit): ");
userBet = inScanner.nextInt();
if (userBet > currentPool || userBet < 0) {
System.out.println("Your bet MUST be between 0 and " + currentPool + " dollars");
userBet = -1;
}
if (userBet == 0) {
System.out.println("You have " + currentPool + " dollars left.");
System.out.println("Goodbye!");
}
}
return userBet;
}
// Given a Scanner, prompt the user for a single character indicating whether
// they
// would like to bet High ('H'), Low ('L') or Sevens ('S'). Your code should
// accept
// either capital or lowercase answers, but should display an error if the user
// attempts
// to enter anything but one of these 3 values and prompt for a valid answer.
// Return the character to the calling program.
private static char getHighLow(Scanner inScanner) {
Scanner keyboard = new Scanner(System.in);
int i = 0;
String userChoice = "";
while (i == 0) {
System.out.println("High, low or sevens (H/L/S): ");
userChoice = keyboard.nextLine();
if (userChoice.length() > 1 || (userChoice.charAt(0) != 'H' && userChoice.charAt(0) != 'h'
&& userChoice.charAt(0) != 'L' && userChoice.charAt(0) != 'l' && userChoice.charAt(0) != 'S'
&& userChoice.charAt(0) != 's')) {
System.out.println("ERROR: You must type H, L, or S.");
} else {
i++;
}
}
char highLow = 'N';
if (userChoice.charAt(0) == 'H' || userChoice.charAt(0) == 'h') {
highLow = 'H';
} else if (userChoice.charAt(0) == 'L' || userChoice.charAt(0) == 'l') {
highLow = 'L';
} else {
highLow = 'S';
}
return highLow;
}
// Produce a random roll of a single six-sided die and return that value to the
// calling
// program
private static int getRoll() {
int dieOne = (int) (Math.random() * 6 + 1);
System.out.println("Die 1 rolls: " + dieOne);
int dieTwo = (int) (Math.random() * 6 + 1);
System.out.println("Die 2 rolls: " + dieTwo);
int rollSum = dieOne + dieTwo;
System.out.println("The total of two dice is: " + rollSum);
return rollSum;
}
// Given the choice of high, low or sevens, the player's bet and the total
// result of
// the roll of the dice, determine how much the player has won. If the player
// loses
// the bet then winnings should be negative. If the player wins, the winnings
// should
// be equal to the bet if the choice is High or Low and 4 times the bet if the
// choice
// was Sevens. Return the winnings to the calling program.
private static int determineWinnings(char highLow, int bet, int roll) {
int highLowValue = 0;
int winnings = 0;
if (highLow == 'H') {
highLowValue = 8;
} else if (highLow == 'L') {
highLowValue = 6;
} else {
highLowValue = 7;
}
if (roll >= 8 && highLowValue == 8) {
winnings = bet;
System.out.println("You won " + winnings + " dollars!");
} else if (roll <= 6 && highLowValue == 6) {
winnings = bet;
System.out.println("You won " + winnings + " dollars!");
} else if (roll == 7 && highLowValue == 7) {
winnings = bet * 4;
System.out.println("You won " + winnings + " dollars!");
} else {
winnings = -1 * bet;
}
return winnings;
}
You can assign the output of each method to variable or call methods directly on determineWinnings.
plan 1)
int userBet = getBet(keyboard, currentPool);
char highLow = getHighLow(keyboard);
int roll = getRoll();
determineWinnings(highLow, userBet, roll);
plan 2)
determineWinnings(getHighLow(keyboard), getBet(keyboard, currentPool), getRoll());
There are following approaches to get the result of one method to another.
Pass result of one method to another
Define private/static members
Better way would be passing result of one method to another method.
I would like to ask why the program prints already the answer? Even if I select on different Difficulty it is still the same.
import java.util.Scanner;
import java.util.Random;
public class GuessigGame {
public static int level(int y) {
Random ans = new Random();
int easy = 20, medium = 50, hard = 10, x;
Scanner in = new Scanner(System.in);
System.out.println("Choose Difficulty");
System.out.println("1. easy ");
System.out.println("2. medium ");
System.out.println("3. hard ");
x = in.nextInt();
switch (x) {
case 1:
System.out.println("Easy");
y = easy;
break;
case 2:
System.out.println("Medium");
y = medium;
break;
case 3:
System.out.println("Hard");
y = hard;
break;
default:
break;
}
return y;
}
public static void main(String[] args) {
int choice, difficulty = 0, answer = -1;
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println("\n\n1. Play Game");
System.out.println("2. Exit");
System.out.println("");
choice = in.nextInt();
int diff = 0, tries = 0, triesbot = 0, trieshu = 0;
diff = level(difficulty);
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch (choice) {
case 1:
while (win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);
answer = in.nextInt();
if (answer == difficulty + 1 || answer == difficulty - 1) {
System.out.println("so close");
} else if (answer == difficulty + 2 || answer == difficulty + 2) {
System.out.println("youre answer was close");
} else if (answer == difficulty + 3 || answer == difficulty - 3) {
System.out.println("try more youre close");
} else if (answer == difficulty + 4 || answer == difficulty - 4) {
System.out.println("try youre best buddy!");
} else if (answer > difficulty + 4 || answer < difficulty - 4) {
System.out.println("so far!");
} else if (tries == 0) {
System.out.print("Game Over!");
win = true;
} else if (answer == difficulty) {
System.out.println("You got the correct answer!!!!");
win = true;
} else {
}
tries++;
}
break;
default:
System.exit(0);
break;
}
}
}
This is the output of the program:
Because you told the computer to print out the difficulty. I suggest having better names.
difficulty = 1 + rand.nextInt(diff);
boolean win = false;
switch(choice) {
case 1:
while(win != true) {
System.out.println(difficulty);
System.out.println("Tries: " + tries);
Paper rock scissors java program.
Ok so the only problem I'm having now is the player's score doesn't update until the second loop around. Any suggestions?
Thanks again Radiodef for your help!!
Updated code below.......
import java.util.Scanner;
public class RPS_Game {
public static void main(String[] args) {
char r = 'R';
char p = 'P';
char s = 'S';
char player1 = 0;
char player2 = 0;
int player1Score = 0;
int player2Score = 0;
int playCount = 0;
Scanner scan = new Scanner(System.in);
while(playCount < 3) {
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player1 = scan.nextLine().toUpperCase().charAt(0);
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player2 = scan.nextLine().toUpperCase().charAt(0);
int winner = winningPlayer(player1, player2);
if(winner == 0) {
System.out.print("\nIt's a tie. Nobody wins!\n");
System.out.println("\nPlayer 1: " + (player1Score += 0));
System.out.println("\nPlayer 2: " + (player2Score += 0));
}
if(winner == 1) {
System.out.print("\nPlayer 1 wins!!\n");
System.out.println("\nPlayer 1: " + player1Score++);
System.out.println("\nPlayer 2: " + (player2Score += 0));
}
if(winner == 2) {
System.out.print("\nPlayer 2 wins!!\n");
System.out.println("\nPlayer 1: " + (player1Score += 0));
System.out.println("\nPlayer 2: " + player2Score++);
}
playCount++;
}
}
public static int winningPlayer(int player1, int player2) {
//Player 1 wins
int result = 0;
if(player1 == 'R' && player2 == 'S') {
result = 1;
}
else if(player1 == 'P' && player2 == 'R') {
result = 1;
}
else if(player1 == 'S' && player2 == 'P') {
result = 1;
}
//Player 2 wins
else if(player2 == 'R' && player1 == 'S') {
result = 2;
}
else if(player2 == 'P' && player1 == 'R') {
result = 2;
}
else if(player2 == 'S' && player1 == 'P') {
result = 2;
}
return result;
}
}
Well, it seems like first you just need to move the call in to the loop:
while(playCount < 3) {
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player1 = scan.nextLine().toUpperCase().charAt(0);
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player2 = scan.nextLine().toUpperCase().charAt(0);
// recompute the winner each time
int winner = winningPlayer(player1, player2);
...
}
For keeping a score, you could just have a variable for each player:
int player1Score = 0;
int player2Score = 0;
while (...) {
...
if (winner == 1) {
++player1Score;
}
if (winner == 2) {
++player2Score;
}
}
Or you could do something fancier like use an array:
int[] scores = new int[3];
while (...) {
...
++scores[ winner ];
for (int i = 1; i < scores.length; ++i) {
System.out.printf("Player %d score is %d.\n", i, scores[i]);
}
}
I was tasked with making a simple program that will play Rock-Paper-Scissors with the user. Unfortunately, when I try to run the program, my return(sentence+outcome) both returns null. I am new to using methods, so please explain what I am doing wrong here... Thank you!
package rockpaperscissors;
/**
*
* #author Owner
*/
import java.util.Scanner;
import java.io.IOException;
public class RockPaperScissors {
static int weaponChoice;
static int computerChoice;
static int tie = 0;
static int lose = 0;
static int win = 0;
static String outcome;
static String sentence;
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
Scanner userInput = new Scanner(System.in);
System.out.println(" =========================");
System.out.println("====ROCK=PAPER=SCISSORS====");
System.out.println(" =========================");
int playAgain = 1; //sets a play again function
do {
System.out.println("Please select your weapon.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
System.out.println("Choose wisely:");
String choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
do {
if (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3) {
System.out.println("Please choose again, grasshopper. There are only"
+ " three choices.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
}
} while (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3);
if (weaponChoice == 1) {
System.out.println("You have selected Rock as your weapon.");
} else if (weaponChoice == 2) {
System.out.println("You have selected Paper as your weapon.");
} else {
System.out.println("You have selected Scissors as your weapon.");
}
//Computer's Choice
computerChoice = 1 + (int) (Math.random() * ((3 - 1) + 1));
if (computerChoice == 1) {
System.out.println("The computer has chosen Rock.");
} else if (computerChoice == 2) {
System.out.println("The computer has chosen Paper.");
} else {
System.out.println("The computer has chosen Scissors.");
}
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
System.out.println("==SCORES==");
System.out.println("WINS: " + win);
System.out.println("TIES: " + tie);
System.out.println("LOSSES: " + lose);
System.out.println("Press 1 to play again, or any other number to exit.");
String play = userInput.nextLine();
playAgain = Integer.parseInt(play);
} while (playAgain == 1);
}
public static String determineOutcome(String outcome, String sentence) {
sentence = "Your result is: ";
do {
if (weaponChoice == 1 && computerChoice == 1 || weaponChoice == 2 && computerChoice == 2 || weaponChoice == 3 && computerChoice == 3) {
tie++;
outcome = "TIE";
} else if (weaponChoice == 1 && computerChoice == 3 || weaponChoice == 2 && computerChoice == 1 || weaponChoice == 3 && computerChoice == 2) {
win++;
outcome = "You WON!";
} else {
lose++;
outcome = "You LOSE. Better luck next time?";
}
} while (lose <0 || win < 0 || tie < 0);
return(sentence+outcome);
}
}
To make this work, you'll need to replace
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
with
String valueReturned = determineOutcome(outcome, sentence);
System.out.println(valueReturned);
because Java is pass by value, not pass by reference. That means that the determineOutcome method will work with its own copies of outcome and sentence, and not modify the versions that belong to the method that called it.
But also, the method is not actually using the two arguments you pass into it. It would be much less confusing if you just omit the parameters entirely, and change it to public static String determineOutcome() ... and declare String sentence; and String outcome; inside the method.
When calling a function that is returning a result you must either call the function within System.out.println() or assign the result to a variable which you then print.
Option 1:
String result = determineOutcome(outcome, sentence);
System.out.println(result);
or option 2:
System.out.println(determineOutcome(outcome, sentence));
In addition to the points other people made in their answers, it looks like your while loop is never being executed. The variables tie, win and lose are never less than 0, so the condition of the while loop is never true. You can try changing it to:
while (lose <= 0 || win <= 0 || tie <= 0);
But be warned, this will result in an infinite loop, so you may need to rethink your logic. You may not need a loop here, depending on what you're trying to do.