I asked this question before, but I think that because i only included as piece of the code it was unclear. I am writing a program that asks the user what kind of question they want asked, and then they are prompted for an answer to that question. However, even the correct input from the user results in a return of an incorrect answer. Here's the code:
import java.util.Scanner;
public class MascotQuiz {
public static void main(String[] args) {
int score = 0;
String greeting = "In this game, I ask you four questions about mascots for "
+ "US collegiate sports teams."
+ "\nYou get 1 point for each correct answer, "
+ "0 points if you type don't know, "
+ "and you lose a point for wrong answers.";
final String schoolOptions = "University of Michigan, "
+ "University of Nebraska, " + "University of Oklahoma, "
+ "University of Wisconsin";
final String mascotOptions = "Badgers, Cornhuskers, Sooners, Wolverines";
String prompt1 = "\nType 1 and I'll give you the mascot and "
+ "you give give the school. \n"
+ "Type 2 and I'll give you the school and "
+ "you give me the mascot. \n" + "Type 3 and I'll quit.";
System.out.println(greeting);
int questionCount = 1;
String mascotQuestion1, mascotQuestion2, mascotQuestion3, mascotQuestion4;
String schoolQuestion1, schoolQuestion2, schoolQuestion3, schoolQuestion4;
do {
System.out.println(prompt1);
int optionChoice;
Scanner scan = new Scanner(System.in);
optionChoice = scan.nextInt();
if (optionChoice == 1) {
if (questionCount == 1) {
System.out.println("What school do the Badgers belong to?");
mascotQuestion1 = scan.nextLine();
if (mascotQuestion1.equalsIgnoreCase("University of Michigan")) {
score++;
}
else if (mascotQuestion1.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
else if (questionCount == 2) {
System.out.println("What school do the Cornhuskers belong to?");
mascotQuestion2 = scan.next();
if (mascotQuestion2.equalsIgnoreCase("University of Nebrasksa")) {
score++;
}
else if (mascotQuestion2.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
else if (questionCount == 3) {
System.out.println("What school do the Sooners belong to?");
mascotQuestion3 = scan.next();
if (mascotQuestion3.equalsIgnoreCase("University of Oklahoma")) {
score++;
}
else if (mascotQuestion3.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
else {
System.out.println("What school do the Wolverines belong to?");
mascotQuestion4 = scan.next();
if (mascotQuestion4.equalsIgnoreCase("University of Winsconsin")) {
score++;
}
else if (mascotQuestion4.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
}
else if (optionChoice == 2) {
if (questionCount == 1) {
System.out.println("What mascot belongs to the University of Michigan?");
schoolQuestion1 = scan.next();
if (schoolQuestion1.equalsIgnoreCase("Badgers")){
score++;
}
else if (schoolQuestion1.equalsIgnoreCase("don't know")){
score = score + 0;
}
else {
score --;
}
}
else if (questionCount == 2) {
System.out.println("What mascot belongs to the University of Nebraska?");
schoolQuestion2 = scan.next();
if (schoolQuestion2.equalsIgnoreCase("Cornhuskers")){
score++;
}
else if (schoolQuestion2.equalsIgnoreCase("don't know")){
score = score + 0;
}
else {
score --;
}
}
else if (questionCount == 3) {
System.out.println("What mascot belongs to the University of Oklahoma?");
schoolQuestion3 = scan.next();
if (schoolQuestion3.equalsIgnoreCase("Sooners")){
score++;
}
else if (schoolQuestion3.equalsIgnoreCase("don't know")){
score = score + 0;
}
else {
score --;
}
}
else {
System.out.println("What mascot belongs to the University of Wisconsin?");
schoolQuestion4 = scan.next();
if (schoolQuestion4.equalsIgnoreCase("Wolverines")){
score++;
}
else if (schoolQuestion4.equalsIgnoreCase("don't know")){
score = score + 0;
}
else {
score --;
}
}
}
else {
questionCount = 5;
}
questionCount ++;
} while (questionCount <= 4);
System.out.println("\nBye. Your score is " + score);
}
}
I think your code is not taking the user answers correctly,it is just prompting the question and immediately print your prompt1 again and not giving the chance for answer. That's why it is not matching your answer and just going in the else loop where your score get decrease.
Another thing in your each if/ else statement you are using scan.next() that's why it is just reading only one word not a line.
I just make few changes in your code and it is running. I made few change in your if else condition do the same with others. I hope it will work for you -
Scanner scan ; // declare scanner reference here and use later
do {
System.out.println(prompt1);
int optionChoice;
scan = new Scanner(System.in); // create new scanner object
optionChoice = scan.nextInt();
if (optionChoice == 1) {
if (questionCount == 1) {
System.out.println("What school do the Badgers belong to?");
scan = new Scanner(System.in); // create new scanner object, it will allow user to enter answer
mascotQuestion1 = scan.nextLine(); // use nextline it will read full line otherwise it is just reading "university" not full answer
if (mascotQuestion1.equalsIgnoreCase("University of Michigan")) {
score++;
}
else if (mascotQuestion1.equalsIgnoreCase("don't know")) {
score = (score + 0);
}
else {
score--;
}
}
else if (questionCount == 2) {
System.out.println("What school do the Cornhuskers belong to?");
scan = new Scanner(System.in); // create new scanner object, it will allow user to enter answer
mascotQuestion2 = scan.nextLine();// use nextline it will read full line otherwise it is just reading "university" not full answer
if (mascotQuestion2.equalsIgnoreCase("University of Nebrasksa")) {
score++;
}
else if (mascotQuestion2.equalsIgnoreCase("don't know")) {
score = (score + 0);
System.out.println("score 2****----"+score);
}
else {
score--;
}
}
Related
I'm trying to start the game over if the user enters "Yes". I tried using a while loop, but it's gone wrong somewhere that I can't find.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
int playerScore = 0;
int computerScore = 0;
int round = 0;
String decision;
// Get user input
while (round<3) {
System.out.println("Please enter your move: Rock, Paper or Scissors");
System.out.println(">>");
Scanner input = new Scanner(System.in);
String playerMove = input.next();
// Check if user input is valid
if (!playerMove.equalsIgnoreCase("Rock") && !playerMove.equalsIgnoreCase("Paper") && !playerMove.equalsIgnoreCase("Scissors")) {
System.out.println("Move is invalid, Opponent gets a point");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else {
// Randomly generate computerMove
int computerInt = (int)(Math.random()*3);
String computerMove = " ";
if (computerInt == 0) {
computerMove = "Rock";
} else if (computerInt == 1) {
computerMove = "Paper";
} else if (computerInt == 2) {
computerMove = "Scissors";}
System.out.println("Opponent move is "+ computerMove);
// Establish winning or losing scenarios
if (playerMove.equalsIgnoreCase(computerMove)) {
System.out.println("Tied");
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else if (playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Scissors") ||
playerMove.equalsIgnoreCase("Scissors") && computerMove.equalsIgnoreCase("Paper") ||
playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Paper")) {
System.out.println("You won");
playerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
else {
System.out.println("You lost");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
}
// Determine the last winner
if (playerScore < computerScore) {
System.out.println("You lose, so sad ;(");
} else if (playerScore > computerScore) {
System.out.println("You win, here's a cookie ;) ");
} else {
System.out.println("Tied, maybe try harder ^_^"); }
}
System.out.println("Do you wanna play again?");
}
}
}
Sounds like this might be a HW or Test question, so just writing steps to help you out:
first have a user-decision variable and initialize it to "Y"
then put the game in a while(user-decision="Y") loop
at the end of this loop ask the user for their decision and update the user-decision variable to either Y or N
if they say Y loop continues, else it ends
if you need to repeat your code, put it in a new class (Game) and instantiate in main () and call until your Game class returns TRUE (press Y)
package appMain;
import java.util.Scanner;
public class Game {
public Boolean PlayGame() {
System.out.println("START GAME");
//
// >> PUT THERE YOUT GAME CODE <<
//
Scanner input = new Scanner(System.in);
String answer = input.next();
if(answer.equals("Y")) {
return true;
}
return false;
}
}
package appMain;
public class GameMain {
public static void main(String args[]) {
Game game = new Game();
while (game.PlayGame()) {
}
System.out.println("GAME finish");
}
}
This is my nim game (goal is dont be the last person to pick up marbles), can someone please guide me. In playing the game, I have just one question
How can I keep track of whose turn it is, I guess if I can keep track of that I can monitor my remainingMarbles. This is the crux of my code. Please help
public class Nim{
public static void main(String[] args)
{
System.out.println("************** Welcome to the game of Nim *******************");
System.out.println("The object of this game is to make me take the last marble off the table");
System.out.println("You must take at least 1 and you can take up to 3 marbles on your turn");
System.out.println("You can go first");
Scanner scan = new Scanner(System.in);
final int MARBLES = 13;
int remainingMarbles;
String input;
do {
//boolean whoseTurn = true;
remainingMarbles = MARBLES;
System.out.println("There are " + MARBLES + " marbles on the table");
while (remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
}
if (1 <= remainingMarbles && remainingMarbles <= 2 && remainingMarbles < 0) {
System.out.println("Congratulations! you won!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
} else
System.out.println("Hard luck you lose!");
System.out.println("Want to play again? y/n");
input = scan.nextLine();
input = input.toLowerCase();
}while (input.charAt(0) == 'y');
}
private static int getUserSelection()
{
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter 1, 2 or 3");
int userSelection = scan.nextInt();
if (isValidMove(userSelection)){
return userSelection;
}
else {
System.out.println("Not a valid entry");
}
}while (true);
}
private static boolean isValidMove(int input)
{
return 1 <= input && input <= 3;
}
private static int getComputerSelection ()
{
Random generator = new Random();
int computerSelection = 1 + generator.nextInt(3);
System.out.println("The computer chooses " + computerSelection);
return computerSelection;
}
}
First, make a boolean before the loop.
boolean whoseTurn = true;
When the variable is true it's the first player's turn, otherwise the second player's turn.
Now inside the while loop we change the variable at the end of every repetition:
whoseTurn = !whoseTurn;
(Which is a faster way of this)
if(whoseTurn) whoseTurn = false;
else whoseTurn = true;
To conclude, you should do something like that:
...
boolean whoseTurn = true;
while(remainingMarbles > 0){
remainingMarbles -= getUserSelection();
System.out.println("There are " + (remainingMarbles -= getComputerSelection()) + " marble(s) on the table.");
whoseTurn = !whoseTurn;
}
...
I know I asked a similar question like this earlier (I figured it out though)
*while(!newWord.equalsIgnoreCase(guess))
forloop:
{ while(!newWord.equalsIgnoreCase(guess))
for ( String a : spaces.split("\\s"))
{
count++;
int x = Integer.valueOf(a);
if (x > guess.length())
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0))
{
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
if(count < spaces.split("\\s").length - 1)
{
break forloop;
}
}
if (count == spaces.split("\\s").length)
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
break;
}*
but now the break command that I have at the third if statement after the for loop just takes me back to the loop towards the beginning of my whole code
*while(!newWord.equalsIgnoreCase(guess))
innerloop:
{ while(true)
{
System.out.println("Please enter the letter you want to guess");
String letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if(!Character.isLetter(letterInput.charAt(0)))
{
System.out.println("Your input is not valid, try again");
break;
}
if(letterInput.equalsIgnoreCase("solve"))
{
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord))
{
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
}
else
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
As you can see I placed labels on the loops I specifically want to go back to. My break is currently taking me back to my innerloop label BUT I want it to take me back to my forloop label. How exactly do I do that? I tried wrapping the for loop with while loops because thats what worked for me last time but it is not working here. Here is my whole code for reference, I apologize if its hard to read I've only started coding 2 months ago.
package e;
import java.util.Scanner;
public class HangmanBeta{
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n");
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
int amountOfSpaces = 0;
String response = "";
String guess = "";
String newGuess = "";
String s = "";
int count = 0;
String newWord = "loops";//RandomWord.newWord();
int guesses = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
if (diff.equalsIgnoreCase("e"))
{
guesses = 15;
}
if(diff.equalsIgnoreCase("i"))
{
guesses = 12;
}
if(diff.equalsIgnoreCase("h"))
{
guesses = 15;
}
if (testingMode == true)
{
System.out.println("The secret word is:" + " " + newWord);
}
System.out.println("The word is:" + " " + guess);
while(!newWord.equalsIgnoreCase(guess))
innerloop:
{ while(true)
{
System.out.println("Please enter the letter you want to guess");
String letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if(!Character.isLetter(letterInput.charAt(0)))
{
System.out.println("Your input is not valid, try again");
break;
}
if(letterInput.equalsIgnoreCase("solve"))
{
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord))
{
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
}
else
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Please enter the spaces you want to check (seperated by spaces)");
String spaces = keyboard.next();
amountOfSpaces = spaces.length();
if (diff.equalsIgnoreCase("e"))
{
if(amountOfSpaces != 7)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("i"))
{
if(amountOfSpaces != 5)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("h"))
{
if(amountOfSpaces != 3)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
{
while(!newWord.equalsIgnoreCase(guess))
forloop:
{ while(!newWord.equalsIgnoreCase(guess))
for ( String a : spaces.split("\\s"))
{
count++;
int x = Integer.valueOf(a);
if (x > guess.length())
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0))
{
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
if(count < spaces.split("\\s").length - 1)
{
break forloop;
}
if (count == spaces.split("\\s").length)
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
break;
}
if (guesses == 0)
{
System.out.println("You have failed to guess the word....:(");
System.out.print("Would you like to play again? Yes(y) or No(n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
} }
if (newWord.equalsIgnoreCase(guess))
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if (response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Your Guess is in the word");
}
if(guesses == guesses - 1)
{
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
break innerloop;
//System.out.print(spaces.split("\\s").length);
//System.out.println("Your Guess is in the word");
//System.out.println();
//System.out.println("Updated word " + guess);
//System.out.println("Guesses Remaining: " + guesses);
}
}
}
}
}
}
}
}
... but now the break command that I have at the third if statement after the for loop just takes me back to the loop towards the beginning of my whole code.
Actually, no.
A break never takes you back. It always takes you forward. In this case it takes you forward to immediately after the block with the label that you broke. For example:
while (....) {
label: while (...) {
...
if (...) break label;
...
}
// Breaks to HERE
}
You may then go back because of something in the context you went to. But it is the context that does it, not the break.
Unfortunately, I can't figure out how to apply this to your example because 1) you don't explain what the code is supposed to do, 2) it is hard to figure out which of the versions you refer to, 3) the code is not compilable, and 4) the readability issues make my head hurt.
So unless you can figure out how to make your code more readable, that is all the help I can give you.
Alright, I have a class assignment to create 3 predetermined methods for a rock, paper, scissors program written by the teacher. However, when I run the program it running the methods multiple times in a row. I've looked through the code several times and can't figure out the problem.
Below is the teacher provided portion of the program:
public class Game
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
RockPaperScissors rps = new RockPaperScissors (); //***Your class
int numGames = 0;
String userChoice = "";
String cpuChoice = "";
String winner = "";
int userWins = 0;
int cpuWins = 0;
System.out.println("Welcome to Rock, Paper, Scissors!\n");
//Get odd number of games
System.out.println("How many rounds would you like to play?");
numGames = in.nextInt();
while (numGames % 2 == 0) //Even number
{
System.out.println("Sorry, number of games must be odd. Please try again:");
numGames = in.nextInt();
}
//Flush the buffer
in.nextLine();
//Play the game for the number of rounds the user entered
for (int i = 1; i <= numGames; i++)
{
//Get the user and computer choices
userChoice = rps.getUserChoice(); //***Your method
cpuChoice = rps.getCPUChoice(); //***Your method
System.out.println("Computer chooses " + cpuChoice);
//Pick winner
winner = rps.pickWinner(userChoice, cpuChoice); //***Your method
if (winner.equalsIgnoreCase("Tie"))
{
System.out.println("It's a tie! Play again.");
numGames++;
}
else
{
if (winner.equalsIgnoreCase("User"))
{
userWins++;
}
else if (winner.equalsIgnoreCase("Computer"))
{
cpuWins++;
}
else
{
System.out.println("Error in picking winner");
}
System.out.println(winner + " wins!");
}
} //end for
//Print results
System.out.println("\nUser wins: " + userWins);
System.out.println("Computer wins: " + cpuWins);
if (userWins > cpuWins)
{
System.out.println("\nThe user won!");
}
if (cpuWins > userWins)
{
System.out.println("The computer won!");
}
//Close game
System.out.println("\nThank you for playing!");
} //end main
} //end class
And here is my code which I'm assuming where the problem is coming from:
public class RockPaperScissors {
public String getUserChoice() {
Scanner sc = new Scanner (System.in);
System.out.println("Enter your choice:");
String userInput = sc.nextLine();
boolean end = true;
while (end == true){
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
end = false;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
userInput = sc.next();
}
}
return userInput;
}// end getUsechoice
public String getCPUChoice() {
String computerChoice = " ";
Random rand = new Random();
int randomNum = rand.nextInt(3) + 1;
if (randomNum == 1){
computerChoice = "rock";
}
else if (randomNum == 2){
computerChoice = "paper";
}
else if (randomNum == 3){
computerChoice = "scissors";
}
return computerChoice;
}
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (getUserChoice().equalsIgnoreCase("rock")) {
if (getCPUChoice().equalsIgnoreCase("rock")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("paper")){
result = "Computer";
}
else if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (getUserChoice().equalsIgnoreCase("paper")){
if (getCPUChoice().equalsIgnoreCase("paper")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("rock")){
result = "User";
}
else if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (getUserChoice().equalsIgnoreCase("Scissors")){
if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("rock")){
result = "Computer";
}
else if (getCPUChoice().equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
}//end pickWinner
}//end rockPaperScissors
Here would be a sample session of the program:
Welcome to Rock, Paper, Scissors!
How many rounds would you like to play? 1 Enter your choice: rock
Computer chooses paper Enter your choice: rock Enter your choice: rock
Computer wins!
User wins: 0 Computer wins: 1 The computer won!
Thank you for playing!
Here I'm wondering why it continues asking for user input multiple times. Also it runs the other methods as well which is why the computer won despite picking paper vs rock.
Alright added in the final changes to my program and it's working perfectly now:
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (userChoice.equalsIgnoreCase("rock")) {
if (cpuChoice.equalsIgnoreCase("rock")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("paper")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (userChoice.equalsIgnoreCase("paper")){
if (cpuChoice.equalsIgnoreCase("paper")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "User";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (userChoice.equalsIgnoreCase("Scissors")){
if (cpuChoice.equalsIgnoreCase("scissors")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
}//end pickWinner
The problem seems to be that when I called in getCPUChoice or getUserChoice it would rerun the program and then change the final answers.
You calling getUserChoice() in the pickWinner method. It should be the userChoice method parameter you should be checking.
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (userChoice.equalsIgnoreCase("rock")) {
if (cpuChoice.equalsIgnoreCase("rock")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("paper")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (userChoice.equalsIgnoreCase("paper")){
if (cpuChoice.equalsIgnoreCase("paper")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "User";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (userChoice.equalsIgnoreCase("Scissors")){
if (cpuChoice.equalsIgnoreCase("scissors")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
You should ask for user input in each loop and not just once.
public class RockPaperScissors {
public String getUserChoice() {
Scanner sc = new Scanner (System.in);
System.out.println("Enter your choice:");
//not here
String userInput;
while (true){
//this is the right place
userInput = sc.nextLine();
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
break;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
}
}
return userInput;
}// end getUsechoice
//...
}//end rockPaperScissors
try changing this in your else part
userInput = sc.next();
to this
userInput = sc.nextLine();
So it will go to next line
So the resulting code ll be
while (end == true){
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
end = false;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
userInput = sc.nextLine();
}
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 7 years ago.
Here is the particular function I am having trouble with.
static boolean check(double money)
{
String scont, yes = "yes", no = "no";
boolean bcont;
if (money == 0) {
System.out.println("You are broke and can no longer play.");
bcont = false;
return bcont;
}
System.out.println("You have " + form.format(money) + " left.");
System.out.println("Would you like to continue playing? (Yes or no?)");
scont = in.nextLine();
if (scont.equalsIgnoreCase(yes)) {
bcont = true;
return bcont;
}
else if (scont.equalsIgnoreCase(no)) {
bcont = false;
return bcont;
}
else {
System.out.println("Invalid answer.");
bcont = check(money);
return bcont;
}
}
Here is the whole program.
import java.util.Random;
import java.util.Scanner;
import java.text.*;
public class JS4B
{
static Scanner in = new Scanner(System.in);
static DecimalFormat form = new DecimalFormat("$#.00");
public static void main(String [] args)
{
int roundnum = 1;
double beginmoney, money;
boolean cont;
intro();
beginmoney = hmmoney();
money = beginmoney;
do{
System.out.println("\nRound " + roundnum + ":");
System.out.println("-------\n");
money = round(money);
cont = check(money);
}while(cont == true);
if (money > beginmoney) {
System.out.println("Congratulations! You have completed " +
rounds(roundnum) + " and ended up with more money than you started!");
}
else if (money == beginmoney) {
System.out.println("You broke even! You have completed " +
rounds(roundnum) + ".");
}
else if (money != 0) {
System.out.println("You have less money than you started with, but " +
"at least you didn't lose it all. You completed " + rounds(roundnum) + ".");
}
else {
System.out.println("You have completed " + rounds(roundnum) + ".");
}
System.out.println("You started with " + form.format(beginmoney) +
" and ended with " + form.format(money));
}
static void intro()
{
System.out.println(" Guess the Number! ");
System.out.println("===========================");
System.out.println("In this game, a random \n" +
"number between 1 and 100 \n" +
"will be chosen. You have to \n" +
"guess what it is in 4 tries.\n");
}
static double hmmoney()
{
double money;
System.out.print("How much money would you like to start with?\nI would like" +
" to start with... ");
money = in.nextDouble();
System.out.println("");
return money;
}
static double round(double money)
{
int guess, actual, guessnum = 1;
double bet = bet(money);
boolean correct;
actual = genint();
for (;;)
{
guess = guess();
correct = check(guess, actual);
if (correct == false) {
guessnum++;
if (guessnum > 4) {
System.out.println("You have made the max number of guesses " +
"and have lost this round.");
System.out.println("The correct number was... " + actual + "\n");
money -= bet;
break;
}
else {
hint(guess, actual);
}
}
else {
money += bet;
break;
}
}
return money;
}
static double bet(double money)
{
double bet;
System.out.print("How much money would you like to bet? ");
bet = in.nextDouble();
System.out.println("");
if (bet > money) {
System.out.println("You can't bet more than you have!");
bet = bet(money);
}
return bet;
}
static int genint()
{
Random gen = new Random();
int actual;
actual = gen.nextInt(100) + 1;
return actual;
}
static int guess()
{
int guess;
System.out.print("I think that the number is... ");
guess = in.nextInt();
System.out.println("");
return guess;
}
static boolean check(int guess, int actual)
{
if (guess != actual) {
System.out.println("That is incorrect.");
return false;
}
else {
System.out.println("Congratulations! You guessed the correct number!");
return true;
}
}
static boolean check(double money)
{
String scont, yes = "yes", no = "no";
boolean bcont;
if (money == 0) {
System.out.println("You are broke and can no longer play.");
bcont = false;
return bcont;
}
System.out.println("You have " + form.format(money) + " left.");
System.out.println("Would you like to continue playing? (Yes or no?)");
scont = System.in.readline();
if (scont.equalsIgnoreCase(yes)) {
bcont = true;
return bcont;
}
else if (scont.equalsIgnoreCase(no)) {
bcont = false;
return bcont;
}
else {
System.out.println("Invalid answer.");
bcont = check(money);
return bcont;
}
}
static void hint(int guess, int actual)
{
if (guess > actual) {
System.out.println("Guess lower!");
}
else {
System.out.println("Guess higher!");
}
}
static String rounds(int roundnum)
{
String result;
if (roundnum == 1) {
result = "1 Round";
return result;
}
else {
result = Integer.toString(roundnum) + " Rounds";
return result;
}
}
}
By the way, this is for my AP Java class, that's why the program is what it is.
In that function, it will bypass the user input and go right to the else statement after it. Then, it will call itself and will take user input after that.
So, in this part of the code:
do{
System.out.println("\nRound " + roundnum + ":");
System.out.println("-------\n");
money = round(money);
cont = check(money);
}while(cont == true);
round() and check() are both functions which use the Scanner object that is declared as a field in your class. round() uses nextInt(), while check() uses nextLine().
What's happening is that when round() is parsing out the guesses, nextInt() doesn't parse out any trailing whitespace after the number input (like a newline from pressing Enter). So, when you call check(), there's still a line for it to read in, and so when you hit this line
scont = in.nextLine();
it reads in that line instead, and since it's obviously not equal to "yes" or "no", it goes to the else block, where it then calls itself.
Since this is for class, I won't actually say how to fix this.
You can not have in the else section:
System.out.println("Invalid answer.");
bcont = check(money);
return bcont;
...because you are unnecessarily making a recursive call, which I am sure that's not what you want.
Hence, do something like this instead:
scont = System.in.readline();
do {
scont = System.in.readline();
if (scont.equalsIgnoreCase(yes)) {
bcont = true;
return bcont;
} else if (scont.equalsIgnoreCase(no)) {
bcont = false;
return bcont;
} else {
System.out.println("Invalid answer. Please try again. Would you like to continue playing? (Yes or no?)");
scont = System.in.readline();
} while (!scont.equalsIgnoreCase(yes) && !scont.equalsIgnoreCase(yes));
I recently had a similar problem working with the Scanner, and as Dennis explained, I'm pretty sure it has something to do with previous uses of the Scanner in the execution. Here is a link the question I posted about it.
Try/Catch inside While in static main method
Take a look at some of the answers given there. There's one in particular which visually explains how the Scanner does it's thing which I learned a lot from.