How can I start the program over again - java

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");
}
}

Related

Best way to code my unintelligent Nim game?

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;
}
...

OverLoading Methods Var cannot be resolved.

The errors I am getting are "answer cannot be resolved". 1/4th of the way down the page. Looked online still don't see what it should be. Would it be easier to use the while loop instead? skipping the do loop completely?
import java.util.Scanner;
public class RPSS{
//Main method
public static void main(String[ ] argc)
{
Scanner tnt = new Scanner(System.in);
String computerHand; // string variable for computer choice
String userHand; // string variable for user choice
// do loop begining
do
{
computerHand = computerHand();
userHand = userHand();
String winner = getWinner(computerHand, userHand);
System.out.println(winner);
System.out.print("User picks" + userHand );
System.out.println("Computer picks " + computerHand );
System.out.println("play again?");
String answer = tnt.next();
//Condition for the do-while loop HERE IS THE ERROR LOCATION
}while (!answer.Equals("No") && (!answer.Equals("no"))); //condition for while loop
String answer = tnt.next();
}
public static String userHand(){ //method for users choice in the game
//prints message to user giving them choices
System.out.println("Lets play rock paper scissors");
System.out.println("1. Rock ");
System.out.println("2. Paper ");
System.out.println("3. Scissors ");
int userChoice; // user choice variable in this method
Scanner tnt = new Scanner(System.in); // creates instance of scanner class
userChoice = tnt.nextInt(); //reads user input
return getChoice(userChoice); //returns user choice to master choice
}
public static String computerHand() //method for computer generated choice
{
int computernum = (int)(Math.random() * (( 3) + 1));
return getChoice(computernum);
}
public static String getChoice(int num) //method recieving both computer hand and user hand
{
// if statements to place the correct choice
String choice = "";
if (num == 1){
choice = "rock";
}
else if(num == 2){
choice = "paper";
}
else if(num == 3){
choice = "scissors";
}
return choice;
}
// Method determing the winner
public static String getWinner(String computerChoice, String userChoice)
{
computerChoice = computerHand(); //places computerChoice variable in computerhand
userChoice = userHand(); //does same for user choice
String winner="";
System.out.println( " the comp chose" + computerChoice);
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println("The computer"); }
else if (userChoice.equals("Paper") && computerChoice.equals("Scissors")){
System.out.println(" The computer wins");
}
else if (userChoice.equals("Scissors") && computerChoice.equals("Rock")){
System.out.println(" The computer wins ");
}
else if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println(" The computer wins ");
}
if (userChoice.equals(computerChoice))
{
System.out.println(" There is no winner");
}
return winner;
}
}
Use tnt.next() which returns the next string. there is no such thing as nextString().
Also, add return winner; at the end of getwinner method.
You declared answer inside the braces of your do and then tried to use it outside the braces. Once you left the braces, the variable was out of scope.

Rock paper scissors, play again?

For my assignment I'm supposed make the program rock paper scissors which I figured that out my main problem is I can't get the program to play again right or get the program to calculate the game scores correctly pleas help I'm going crazy trying to figure this out?!
//Tayler Dorsey
import java.util.Random;
import java.util.Scanner;
public class PRS {
static Scanner keyboard = new Scanner(System. in );
public static void instructions() {
System.out.println("This is the popular game of paper, rock, scissors. Enter your\nchoice by typing the word \"paper\", the word \"rock\" or the word\n\"scissors\". The computer will also make a choice from the three\noptions. After you have entered your choice, the winner of the\ngame will be determined according to the following rules:");
System.out.println("Paper wraps rock (paper wins)\nRock breaks scissors (rock wins)\nScissors cuts paper (scissors wins)");
System.out.println("If both you and the computer enter the same choice, then the game is tied.");
}
public static int playGame() {
int ties = 0, wins = 0, losts = 0;
String userchoice, computerchoice;
System.out.println("Enter your choice: ");
userchoice = keyboard.next();
computerchoice = computerChoose();
System.out.println("You entered: " + userchoice);
System.out.println("Computer choose: " + computerchoice);
if ((userchoice.equals("paper") && computerchoice.equals("paper")) || (userchoice.equals("rock") && computerchoice.equals("rock")) || (userchoice.equals("scissors") && computerchoice.equals("scissors"))) {
System.out.println("IT'S A TIE!");
ties++;
return 3;
} else if ((userchoice.equals("paper") && computerchoice.equals("rock")) || (userchoice.equals("rock") && computerchoice.equals("scissors")) || (userchoice.equals("scissors") && computerchoice.equals("paper"))) {
System.out.println("YOU WIN!");
wins++;
return 1;
} else {
System.out.println("YOU LOSE!");
losts++;
return 2;
}
}
public static String computerChoose() {
Random generator = new Random();
String[] answer = new String[3];
answer[0] = "paper";
answer[1] = "rock";
answer[2] = "scissors";
return answer[generator.nextInt(3)];
}
public static void main(String[] args) {
String play;
Scanner keyboard = new Scanner(System. in );
System.out.println("The Game of Paper, Rock, Scissors");
System.out.println("Do you need instructions (y or n)?");
String help = keyboard.nextLine();
if (help.equals("y")) instructions();
int result = playGame();
System.out.println("Play again (y or n)?");
play = keyboard.nextLine();
if (play.equals("y"));
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
do {} while (play == "y"); {
playGame();
int count = 0;
count++;
}
}
}
There are two issues here:
The code isn't inside the do-while loop, it's after it.
String equality should be checked with equals not with ==.
So:
int count = 0;
do { // Note the code inside the do-while block
playGame();
count++;
} while (play.equals("y")); // Note the use of equals
Do the following:
do {
play = keyboard.nextLine();
if (play.equals("y")){
}
else {
int count = 0, wins = 0, losts = 0, ties = 0;
System.out.println("Games played: " + count);
System.out.println("Wins for you: " + wins);
System.out.println("Wins for me: " + losts);
System.out.println("Tied games: " + ties);
}
} while (play.equals("y"));
In order to calculate the games scores make those variable global.
public class PRS {
static Scanner keyboard = new Scanner(System. in );
int ties = 0, wins = 0, losts = 0;

Multiple word string input and boolean

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--;
}
}

Nim game - specify winner

import java.util.Scanner;
/**
*#author Andy
*#verison 21.11.2012
*/
public class NimGame
{
public static void main (String[] args)
{
System.out.println ("********** Hello Welcome to the game Nim *********");
System.out.println (" The game is relatively simple.... ");
System.out.println (" This is a game for two players. ");
System.out.println (" There is a heap containing 10 to 20 stones.");
System.out.println (" Players take turns to remove 1-4 stones ");
System.out.println (" The player who removes the last stone wins. ");
System.out.println ("******************************************************************");
Scanner scan = new Scanner (System.in);
int heapSize = 15;
int stones = 0;
boolean nextInteger = false;
boolean lessThanFour = false;
String player1 = "Player 1";
String player2 = "Player 2";
String player = player1;
System.out.println ("The number of stones currently in the heap is :- " + heapSize);
System.out.println();
while (heapSize > 0)
{
nextInteger = false;
lessThanFour = false;
System.out.println (player + ":" + "how many stones will you take from the heap?");
System.out.println();
while (nextInteger == false && lessThanFour == false)
{
if (scan.hasNextInt())
{
nextInteger = true;
stones = scan.nextInt();
if (stones <=4 && stones >0)
{
System.out.println();
System.out.println ("You picked " + stones);
heapSize = (heapSize - stones);
if (heapSize >= 0)
{
System.out.println();
System.out.println ("There are " + heapSize + "stones left");
System.out.println();
lessThanFour = true;
System.out.println();
if (player.equals(player1))
{
player = player2;
}
else
{
player = player1;
}
}
else
{
System.out.println ("Bad input, please try again");
nextInteger = false;
scan.nextLine();
}
}
else
{
System.out.println ("Bad input, please try again");
scan.nextLine();
}
}
}
}
}
}
I dunno how to implement a way to specify player 1 or player 2 being the winner once the sizeheap (number of stones left) reaches 0. Any help would be appreciated. Also when the sizeheap reaches a negative number, it will display 'bad input' but then any other number inserted after that also displays 'bad input.'
Thanks!
Basically, you just need to rewrite if (heapSize >= 0) so it displays a win message:
if (heapSize > 0) {...} else { ...win... }
Here's the critical part, fixed, streamlined a bit, and edited:
if (stones <= 4 && stones > 0) {
System.out.println ("\nYou picked " + stones);
heapSize = (heapSize - stones);
if (heapSize > 0) {
System.out.println ("\nThere are " + heapSize + " stones left\n\n");
// Could use a ternary operator here:
// player = (player.equals(player1) ? player2 : player1);
if (player.equals(player1)) {
player = player2;
}
else {
player = player1;
}
}
else {
if (player.equals(player1)) {
System.out.println("Player 1 wins!");
}
else {
System.out.println("Player 2 wins!");
}
}
}
Further tips:
You can just use a newline \n instead of an System.out.println().
The lessThanFour flag is probably unnecessary

Categories

Resources