How to fix my RockPaperScissors game written in Java? - java

I'm trying to write a RockPaperScissors game for my Java class but I'm having trouble with my code. When it runs, sometimes it outputs the wrong thing and sometimes it is correct.
For example when the user enters P the computer is either supposed to answer with Tie, My Point, or Your Point, and then under it will say what each of us played. But often it will say some thing like "Your Point!" "R beats R".
import java.util.Scanner;
public class RockPaperScissors
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tie = 0;
int win = 0;
int loss = 0;
String playerChoice;
System.out.println(RockPaperScissors.getComputerChoice());
while (true)
{
System.out.println();
System.out.print("(R)ock, (P)aper, (S)cissors, or quit: ");
playerChoice = input.nextLine();
if (playerChoice.equalsIgnoreCase("quit")) break;
else
//switch statement
if (playerChoice.equalsIgnoreCase(
RockPaperScissors.getComputerChoice()))
{
System.out.println("Tie!");
tie++;
}
else if ((playerChoice.equalsIgnoreCase("R") &&
RockPaperScissors.getComputerChoice().equals("S")) ||
(playerChoice.equalsIgnoreCase("P") &&
RockPaperScissors.getComputerChoice().equals("R")) ||
(playerChoice.equalsIgnoreCase("S") &&
RockPaperScissors.getComputerChoice().equals("P")))
{
System.out.println("Your Point!");
System.out.println(playerChoice + " beats "
+ RockPaperScissors.getComputerChoice());
win++;
}
else if ((playerChoice.equalsIgnoreCase("R") &&
RockPaperScissors.getComputerChoice().equals("P")) ||
(playerChoice.equalsIgnoreCase("P") &&
RockPaperScissors.getComputerChoice().equals("S")) ||
(playerChoice.equalsIgnoreCase("S") &&
RockPaperScissors.getComputerChoice().equals("")))
{
System.out.println("My Point!");
System.out.println(RockPaperScissors.getComputerChoice()
+ " beats " + playerChoice);
loss++;
}
else
{
System.out.println("Invalid Input!");
}
}
System.out.println();
System.out.println("You won " + win + " times.");
System.out.println("You lost " + loss + " times.");
System.out.println("We tied " + tie + " times.");
}
public static String getComputerChoice ()
{
int compChoiceInt;
String compChoice;
compChoiceInt = (int) (Math.random() * 3);
switch (compChoiceInt)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
default:
compChoice = "Invalid Input";
System.out.println("Invalid Input.");
break;
}
return compChoice;
}

You're calling getComputerChoice() many times in your code that decides if the user wins, loses, or ties. That can result in several different possible outcomes to each round because each one of those method calls results in a new choice being randomly generated. Instead of calling that method several times, declare a variable and call it just once, before you compare it to the player's choice.

Related

Need exe file to open console

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

Rock Paper Scissors programme [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have been frustrated with this code. The goal is to create a rock paper scissors game, best of 3. I have tried to make a "while" loop but I've got it all wrong and ended up scrapping it back to what I started with, a non-looping code.
If anyone can enlighten me how to make it loop until the computer or player gets a score of 3 wins, I would be so grateful!! Thank you so much
Sorry I should clarify, it needs to loop until the user or computer has 3 wins, so they rebattle until the user or computer reaches 3 wins
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main(String[] args)
{
Scanner key;
Random randGen;
char userChoice, computerChoice;
int winner, compInt;
int computerScore;
int userScore;
int scoreCounter;
/***** INITIALIZATION SECTION *****/
key = new Scanner(System.in);
randGen = new Random();
userChoice = ' ';
computerChoice = ' ';
//winner = -1;
compInt = -1;
computerScore = 0;
userScore = 0;
scoreCounter = 0;
System.out.println("What is your name?");
String name = key.nextLine();
System.out.println(name + " play rock, paper, or scissors with me!!");
/***** INPUT SECTION *****/
System.out.println("Please enter R for rock, P for paper, or S for scissors:");
userChoice = key.next().toUpperCase().charAt(0);
//key.close();
/***** PROCESSING SECTION *****/
compInt=randGen.nextInt(3);
if (compInt == 0)
{
computerChoice = 'R';
}
else if (compInt == 1)
{
computerChoice = 'P';
}
else if (compInt == 2)
{
computerChoice = 'S';
}
winner = RockPaperScissors.decideWinner(userChoice,computerChoice);
/***** OUTPUT SECTION *****/
System.out.printf("Player: %c%nComputer: %c%n", userChoice, computerChoice);
switch (winner)
{
case 0:
System.out.println("It's a tie!");
System.out.println(name + ": " + userScore + ", Computer:" + computerScore );
break;
case 1:
System.out.println("You won!");
userScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore );
break;
case 2:
System.out.println("Computer won!");
computerScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore );
break;
default:
System.out.println("Invalid choice, try again.");
break;
}
//System.out.println("Thanks for playing!);
}
/***** STATIC METHODS *****/
/**Description: given two characters (R,P, or S) determines winner using rock
* paper rules. Assume input is valid and error checking is done in main
* programme. **/
public static int decideWinner(char p1,char p2)
{
String combo;
combo = String.format("%c%c", p1, p2);
switch(combo)
{
case "RS":
case "PR":
case "SP":
return 1;
case "RP":
case "PS":
case "SR":
return 2;
case "RR":
case "PP":
case "SS":
return 0;
}
return -1;
}
}
/***************************************************
while(userScore == 3)
{
System.out.println("You won the game" +name+ "! Congratulations");
scoreCounter++;
}
while(computerScore == 3)
{
System.out.println("Sorry " +name+ ", Computer won...");
scoreCounter++;
}
**************************************************/
Try splitting your code in methods that each have their own task, that way u can more easily lay out and control the behaviour of your program. E.g. in the case of user input, you can recursively call the method in case of invalid input.
For the while loop, I simply added a counter that increases after every game, until 3.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
private static int totalGames = 0;
public static void main(String[] args)
{
Scanner key;
Random randGen;
char userChoice, computerChoice;
int winner;
int computerScore;
int userScore;
/***** INITIALIZATION SECTION *****/
key = new Scanner(System.in);
randGen = new Random();
computerChoice = ' ';
//winner = -1;
computerScore = 0;
userScore = 0;
System.out.println("What is your name?");
String name = key.nextLine();
System.out.println(name + " play rock, paper, or scissors with me!!");
while(totalGames < 3) {
userChoice = getUserChoice(key, false);
/* PROCESSING SECTION */
computerChoice = getComputerChoice(computerChoice, randGen.nextInt(3));
winner = RockPaperScissors.decideWinner(userChoice, computerChoice);
totalGames++;
/* OUTPUT SECTION */
System.out.printf("Player: %c%nComputer: %c%n", userChoice, computerChoice);
switch (winner) {
case 0:
System.out.println("It's a tie!");
System.out.println(name + ": " + userScore + ", Computer:" + computerScore);
break;
case 1:
System.out.println("You won!");
userScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore);
break;
case 2:
System.out.println("Computer won!");
computerScore++;
System.out.println(name + ": " + userScore + ", Computer:" + computerScore);
break;
default:
System.out.println("Invalid choice, try again.");
break;
}
}
//System.out.println("Thanks for playing!);
}
private static char getComputerChoice(char computerChoice, int compInt) {
if (compInt == 0)
{
computerChoice = 'R';
}
else if (compInt == 1)
{
computerChoice = 'P';
}
else if (compInt == 2)
{
computerChoice = 'S';
}
return computerChoice;
}
private static char getUserChoice(Scanner key, boolean retry) {
char userChoice;
/* INPUT SECTION */
if(retry)
System.out.println("You entered an invalid input, please try again...");
System.out.println("Please enter R for rock, P for paper, or S for scissors:");
try {
userChoice = key.next().toUpperCase().charAt(0);
if(userChoice != 'R' && userChoice != 'P' && userChoice != 'S')
return getUserChoice(key, true);
} catch (Exception e){
return getUserChoice(key, true);
}
return userChoice;
}
/***** STATIC METHODS *****/
/**Description: given two characters (R,P, or S) determines winner using rock
* paper rules. Assume input is valid and error checking is done in main
* programme. **/
public static int decideWinner(char p1,char p2)
{
String combo;
combo = String.format("%c%c", p1, p2);
switch(combo)
{
case "RS":
case "PR":
case "SP":
return 1;
case "RP":
case "PS":
case "SR":
return 2;
case "RR":
case "PP":
case "SS":
return 0;
}
return -1;
}
}
/***************************************************
while(userScore == 3)
{
System.out.println("You won the game" +name+ "! Congratulations");
scoreCounter++;
}
while(computerScore == 3)
{
System.out.println("Sorry " +name+ ", Computer won...");
scoreCounter++;
}
**************************************************/

Java Do While isn't working properly

Sorry I am new to this site so not sure how this will show up. I am trying to make a simple Rock, Paper, Scissors game. After the while statement, if R, P, S isn't entered, the program just does nothing. I want it to loop back to the question at the beginning so a right choice can be entered. Also, how would I enter a print statement like "Invalid Choice Please Retry"?
package rps.gameapp;
import java.util.Scanner;
public class RPSGameApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int randNum = (int) (Math.random() * 3);
do
{
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
switch (randNum)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice))
{
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase(userChoice)
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P"))
{
System.out.println("User Wins");
} else
{
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
} while (playAgain.equalsIgnoreCase("Y"));
System.out.println("Thanks for Playing!");
}
}
It looks like you forgot one do for your inner do while loop.
It should be :
do {
do {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P") && !userChoice.equalsIgnoreCase("R") && !userChoice.equalsIgnoreCase("S"));
...
} while (playAgain.equalsIgnoreCase("Y"));
Without that inner do (and the curly braces surrounding that loop's body), the inner loop becomes a while loop with an empty body.
Like Eran said, you need to wrap your do-while loop in another loop, that will keep asking user for correct input. This is fully working code. One thing that could be better is the message after user inputs wrong letter.
Edit: also make sure you draw random number for every iteration.
Edit 2: to change the message depending on user input you can introduce a new variable that will keep the track of number of times you asked user for correct input. If it is 0- it means user is asked the first time and we should print "Welcome" message. It is anything other than 0- you need to ask the user for correct input. After every round we assign zero to the variable again and the cycle repeats. I have implemented this change in the code. Note that this variable can also be a boolean.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int iterationNumber;
while (true) {
iterationNumber = 0;
do {
if (iterationNumber == 0) {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
} else {
System.out.println("Please enter valid letter.");
System.out.println("Pick R, P, or S.");
}
iterationNumber++;
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
int randNum = (int) (Math.random() * 3);
switch (randNum) {
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice)) {
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase("R")
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P")) {
System.out.println("User Wins");
} else {
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
if (playAgain.equalsIgnoreCase("N")) {
break;
}
iterationNumber = 0;
}
System.out.println("Thanks for Playing!");
}

Nim Game Java errors?

Hi I am programming a game of Nim,
I ha e most of the code complete but I am having two major problems.
I can't find my errors
I can't seem to get the computer to take its turn
Thanks in advance, here is my code.
import java.util.*;
import java.util.Random;
public class Nim {
public static void main(String[] args) {
int banana = 0;
Random r = new Random();
intro();
banana = r.nextInt(16);
int numStones = (15 + banana);
yorner(numStones);
//kbinput.nextInt();
}
public static void intro () {
System.out.println("Welcome to the game of Nim!");
System.out.println("The Rules of the game are as follows: \n");
System.out.println("1. There are two players in this game; you and the computer.");
System.out.println("2. The game starts with a random number stones ranging from 15 to 30 stones.");
System.out.println("3. Every turn each player takes anywhere between 1 to 3 stones");
System.out.println("4. The player who takes the last stone loses. \n");
System.out.println("Would you like to start the game now? \nPlease enter 'Y' for yes and 'N' for no:");
}
public static void yorner (int numStones){
System.out.println("This game of nim will start with " + numStones + " stones.\n");
Scanner kbinput = new Scanner (System.in);
boolean vInput = false;
do
{
String yorn = kbinput.nextLine();
char input = yorn.charAt(0);
switch(input) {
case 'Y':
case 'y':
vInput = true;
yes(numStones);
break;
case 'N':
case 'n':
System.out.println("Thank you for your time.");
vInput = true;
break;
default:
System.out.println("Please only enter 'Y' for yes and 'N' for no, other entries will not be tolerated.");
}
}
while((vInput == false));
}
public static void yes (int numStones){
System.out.println("You selected 'Yes', thank you for choosing to play the game of Nim.\n");
System.out.println("It is your turn first.");
System.out.println("How many stones would you like to take? \n");
System.out.println("Enter a number from 1 to 3");
player(numStones);
}
public static int player(int numStones){
Scanner kbinput = new Scanner (System.in);
int numTake = kbinput.nextInt();
int numStone = 0;
boolean apple = false;
loop: while ( apple == false){
switch(numTake){
case 1:
apple = true;
numStone = numStones - numTake;
System.out.println("There are " + numStone + " stones left");
break;
case 2:
apple = true;
numStone = numStones - numTake;
System.out.println("There are " + numStone + " stones left");
break;
case 3:
apple = true;
numStone = numStones - numTake;
System.out.println("There are " + numStone + " stones left");
break;
default:
System.out.println("You can only takes anywhere between 1 and 3 stones from the pile");
}
}
return numStone;
}
public static boolean compWin (int numStone){
return false;
}
public static void computerTurn(int numStone1, int numStone) {
Random rn = null;
int compTake = rn.nextInt(3);
switch(compTake){
case 1:
System.out.println("Computer takes 1 stone.");
numStone1 = numStone - compTake;
System.out.println("There are " + numStone + " stones left");
break;
case 2:
System.out.println("Computer takes 2 stones");
numStone1 = numStone - compTake;
System.out.println("There are " + numStone + " stones left");
break;
case 3:
System.out.println("Computer takes 3 stones");
numStone1 = numStone - compTake;
System.out.println("There are " + numStone + " stones left");
break;
}
}
}
The errors that I get are these
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, insert ";" to complete LocalVariableDeclarationStatement
Syntax error, insert ";" to complete Statement
I cannot reproduce your compilation error.
However, you do not have a game loop (that is, a loop that keeps the game going while there are still valid moves) and you never invoke the computerTurn

The Pig Dice Game Human vs Computer Java Program

I have been working on this program for about a week now and I think I have it down pack. The issue I am having when I ask the user at the beginning of the game (human vs computer) every time I run the program it asks me what my name is again. Here is what I have thus far:
import java.util.Scanner;
public class Assignment
{
Scanner usersName;
Boolean humanTurn = true;
Boolean computerTurn = true;
int dice;
int humanTurnPoints, computerTurnPoints;
int humanTotalPoints = 0;
int computerTotalPoints = 0;
private Scanner keyboard;
private Scanner key;
//System.out.print("Please enter your name: ");
//usersName = new Scanner(System.in);
//setStart(usersName.nextLine());
public void roll()
{
dice = (int)(Math.random()*6) + 1;
}
public int humanTurnScore()
{
{
humanTurnPoints = dice + humanTurnPoints;
System.out.println("You threw: " + dice);
System.out.println("You have scored: " + humanTurnPoints + " in your turn.");
} return humanTurnPoints;
}
public void humanTurnZero()
{
humanTurnPoints = 0;
}
public int computerTurnScore()
{
{
computerTurnPoints = dice + computerTurnPoints;
System.out.println("Computer has scored: " + computerTurnPoints + " in its turn.");
} return computerTurnPoints;
}
public void computerTurnZero()
{
computerTurnPoints = 0;
}
public Assignment()
{
humanGame();
if(!humanTurn)
{
computerTurn();
}
}
public int humanGame()
{
System.out.println("To start the game please press 'r'.");
key = new Scanner(System.in);
String start = key.nextLine();
if(!start.equalsIgnoreCase("R"))
{
System.out.println("Make sure you are pressing 'r'.");
humanGame();
}
if(start.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets start.");
do{
roll();
if(dice == 1)
{
System.out.println("You got 1 and you lost your turn.");
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
humanTurnZero();
computerTurn();
}
else if(dice != 1)
{
humanTotalPoints += dice;
if(humanTotalPoints >= 100)
{
System.out.println("You threw: " + dice);
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Congratulations, you win!");
System.exit(0);
}
humanTurnScore();
System.out.println("Your GRAND TOTAL score is: " + humanTotalPoints);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("You can hold or roll again.");
System.out.println("To roll again press 'r' or 'h' to hold.");
keyboard = new Scanner(System.in);
String choice = keyboard.nextLine();
if(choice.equalsIgnoreCase("R"))
{
System.out.println("You pressed 'r'.");
System.out.println("Lets roll again.");
roll();
if(!choice.equalsIgnoreCase("R"))
{
System.out.println("You didn't press 'r'. To make sure the program is running correctly please press 'r' to roll or 'h' to hold.");
humanGame();
}
}
if(choice.equalsIgnoreCase("h"))
{
System.out.println("You pressed 'h' and loose your turn.");
System.out.println("Your Grand total is: " + humanTotalPoints);
humanTurnZero();
computerTurn();
}
}
}while(humanTurn);
}return dice;
}
public int computerTurn()
{
System.out.println("Now it's computer turn.");
do {
roll();
if(dice != 1)
{
computerTotalPoints += dice;
if(computerTotalPoints >=100)
{
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Game Over! the computer wins");
System.exit(0);
}
System.out.println("Computer threw: " + dice);
System.out.println("Computer's GRAND TOTAL score is: " + computerTotalPoints);
System.out.println("Your Grand total is: " + humanTotalPoints);
computerTurnScore();
roll();
}
if(dice == 1)
{
System.out.println("Computer thrown 1 therefore it's your turn now.");
computerTurnZero();
humanGame();
}
if(computerTurnPoints >= 20)
{
System.out.println("Computer scored already " + computerTurnPoints + " you'd better start to focus.");
System.out.println("Please play again");
humanGame();
}
}while (computerTurn);
return dice;
}
public static void main(String[] args)
{
new Assignment();
}
}
I commented out (up close to the top of the program) where I am asking the user at the beginning of the program what their name is. I actually need in all the System.out.println where it says 'You' I need it to say the usersName.
Would someone please help me with this program. I know someone is kind enough to help me out here.
Thank you in advance.
Of course it will ask you that every time!
You need to save this in a file, and then read from it!
//Write
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println(usersName.nextLine());
writer.close();
//Read
BufferedReader br = new BufferedReader(new FileReader("the-file-name.txt"));
try {
while (line != null) {
usersName = line;
line = br.readLine();
}
} finally {
br.close();
}
Add your logic for determining if there is sth in that file yourself please.
Okay, I think you might be getting confused about the lifetimes of variables. In java, variables like String username; exist only in their own scope.
If you define a variable inside a method, it will be forgotten about when the program exists the method.
If you define it as a field inside a class (what you were doing), it will only exist as long as the instance of the class exists. As soon as the program forgets about the instance of the class, it also forgets about anything attached to that instance, including its variables.
Once the program shuts down, the computer naturally forgets about all objects that the program held, and so the username ceases to exist.
If you want the program to remember some value across shutdowns, you have to store that value in a file or a database or whatever. I recommend using a file, to make a database for this would be overkill squared. I will refer you to Roberto's answer from an hour ago for more info on how to achieve this exacly.

Categories