How to make java restarts with receive word from keyboard - java

I want to ask the user if they want to play again when they finish a game. Currently, the only way for them to do that is to call the program again; however, I'd like to prompt the user for whether or not they'd like to play again once they finish a game.
public class Hangman
{
Random r;
GetData get;
String[] words = {"eat","what" };
String word;
boolean finished = false;
int badGuessCount=0;
boolean [] foundLetters;
String entryWord =" ";
public Hangman()
{
r = new Random();
get = new GetData();
playAGame();
}
public void playAGame()
{
word = words[r.nextInt(words.length)];
foundLetters = new boolean[word.length()];
while (!finished)
{
showGallows();
showWord();
getGuess();
checkGuess();
if (badGuessCount==6)
{
System.out.print('\u000C');
showGallows();
System.out.println("Sorry, but you lost.");
System.out.println("The word was: "+word);
finished=true;
}
}
}
public void showGallows()
{
System.out.print('\u000C');
if (badGuessCount==0)
man_0();
if (badGuessCount==1)
man_1();
if (badGuessCount==2)
man_2();
if (badGuessCount==3)
man_3();
if (badGuessCount==4)
man_4();
if (badGuessCount==5)
man_5();
if (badGuessCount==6)
completedMan();
System.out.println("\n");
}
public boolean showWord()
{
boolean goodGuess = false;
char ch = entryWord.charAt(0);
for (int lc=0; lc < word.length(); lc++)
if (foundLetters[lc]==true)
{
System.out.print(word.charAt(lc)+" ");
}
else if (word.charAt(lc)==ch)
{
System.out.print(word.charAt(lc)+" ");
foundLetters[lc] = true;
goodGuess = true;
}
else
System.out.print("_ ");
return goodGuess;
}
public void getGuess()
{
System.out.println("\n\n\nWhat letter do you want to guess?");
System.out.println("Type the whole word to guess the word.");
System.out.println("You have "+(6 - badGuessCount)+ "guess left.");
System.out.print("Enter guess");
entryWord = get.aWord();
}
public void checkGuess()
{
boolean goodGuess;
if (entryWord.length()>1)
{
if (entryWord.equals(word))
{
System.out.println("\n\nYes You won!");
finished = true;
System.out.println("close and run if you want to play again!");
String pause = get.aWord();
}
}
else
{
showGallows();
goodGuess = showWord();
if (goodGuess)
{
System.out.println("\n\n\nGood guess");
System.out.println("Press the Enter key to continue!");
String pause = get.aWord();
}
else
{
badGuessCount++;
System.out.println("\n\n\nBad guess!");
System.out.println("Press the Enter key to continue!");
String pause = get.aWord();
}
}
}
//public void completedMan()
}
How can I prompt the user to play again, and then restart the game based on their input?

You'll need to put playAGame(); itself inside a loop.
do
{
playAGame();
} while (UserWantsToKeepPlaying());
private boolean UserWantsToKeepPlaying() {
// Ask the user if they want to keep playing
}
I suggest a do - while loop because you'll always play the game at least once, and you (presumably) don't want to prompt the user to play again until after they finish playing a game.

error at while (UserWantsToKeepPlaying()); what I suppose to do
do
{
playAGame();
} while (UserWantsToKeepPlaying());
}
public boolean UserWantsToKeepPlaying(int number)
{
for (int i = 1; i > number; i--)
if (number % i == 0 && i != number) return false;
else return true;
System.out.print("\n\n Play Again 'No' Press 0 Yes' Press 1 : ");
}

Related

Program keeps printing "keep playing" instead of reading the code

Every time I run my program, if the point limit was not met it is supposed to ask the user to keep playing, and if they choose yes then it is supposed to go back to the loop and run the code again but it is not doing that. when I enter "yes" it just prints the amount of points i currently have rather than going back to the loop.
import java.util.*;
public class Blackjack {
private int points;
private int limit;
private Scanner scan;
public Blackjack() {
scan = new Scanner(System.in);
}
/*Purpose: To print the current points and the limit.
Input: Points and Limit
Output: Points and Limit
*/
public void displayPoints() {
System.out.println("Your points:" + points + "/" + limit);
}
/*Purpose: To ask the user for the game limit.
Input: Game limit
Output: Entered limit
*/
public void startGame() {
System.out.println("Enter point limit:");
limit = scan.nextInt();
displayPoints();
}
/*Purpose: To get the roll value from rolling a dice
Input: Nothing
Output: Random dice number
*/
public int getRoll() {
Random r = new Random();
int roll = r.nextInt(6) + 1;
System.out.println("You rolled:" + roll);
return roll;
}
/*Purpose: To see if the player wants to keep playing the game,
Input: yes or no
Output: User's response.
*/
public boolean askUser(boolean firstTime) {
if (firstTime == true)
System.out.println("Start Playing?");
else {
System.out.println("Keep playing?");
}
scan.next();
return firstTime;
}
/* Purpose: to display the result of points in the game.
Input: No input.
Output: amount of points in the game.
*/
public void displayResult() {
if (points == limit)
System.out.println("BlackJack!");
else if (points > limit)
System.out.println("Bust!");
else if (points < limit)
System.out.println("Stand at " + points + " points!");
}
/*Purpose: to play all methods
Input: none.
Output: Game results.
*/
public void play() {
boolean gameOver = false;
startGame();
askUser(true);
String response = "";
int roll = getRoll();
while (response.equals("yes") && gameOver == false)
getRoll();
points = points + roll;
displayPoints();
if (points >= limit)
gameOver = true;
else {
askUser(false);
}
displayResult();
}
public static void main(String[] args) {
Blackjack practice = new Blackjack();
practice.play();
}
}
You didn't get response when user type.
I think you can change your askUser method like below code.
public String askUser(boolean firstTime) {
if (firstTime == true)
System.out.println("Start Playing?");
else {
System.out.println("Keep playing?");
}
String response = scan.next();
return response;
}
then change play method like :
public void play() {
boolean gameOver = false;
startGame();
String response = askUser(true);
;
;
}
I have made small changes in your code. Try this:
package stack;
import java.util.*;
public class Blackjack{
private int points;
private int limit;
private Scanner scan;
private boolean firstime = true; //new
boolean gameOver; //new
private String answer;//new
public Blackjack(){
scan = new Scanner(System.in);
}
/*Purpose: To print the current points and the limit.
Input: Points and Limit
Output: Points and Limit
*/
public void displayPoints(){
System.out.println("Your points:" + points+"/"+limit);
}
/*Purpose: To ask the user for the game limit.
Input: Game limit
Output: Entered limit
*/
public void startGame(){//Changes
if(firstime == true) {
System.out.println("Start Playing?");
answer = scan.next();
}
switch(answer) {
case "yes":
System.out.println("Enter point limit:");
limit = scan.nextInt();
int roll = getRoll();
points = points + roll;
displayResult();
break;
case "no":
goodBye();
}
}
//New method
public void goodBye() {
System.out.println("Goodbye!");
scan.close();
}
/*Purpose: To get the roll value from rolling a dice
Input: Nothing
Output: Random dice number
*/
public int getRoll(){
Random r = new Random();
int roll = r.nextInt(6)+1;
System.out.println("You rolled:" + roll);
return roll;
}
/* Purpose: to display the result of points in the game.
Input: No input.
Output: amount of points in the game.
*/
public void displayResult(){//Changes
if(points == limit) {
gameOver = true;
System.out.println("BlackJack!");
displayPoints();
System.out.println("Keep playing?");
answer = scan.next();
}
else if (points > limit) {
gameOver = true;
System.out.println("Bust!");
displayPoints();
System.out.println("Keep playing?");
answer = scan.next();
}
else if (points < limit) {
gameOver = false;
System.out.println("Stand at " + points + " points!");
}
}
/*Purpose: to play all methods
Input: none.
Output: Game results.
*/
public void play(){//Changes
startGame();
ENDWHILE:while(gameOver == true || gameOver == false) {
if(answer.equals("yes")) {
firstime = false;
while(gameOver == true) {
points = 0;
startGame();
}
while(gameOver == false) {
startGame();
}
}else {
break ENDWHILE;
}
}
goodBye();
}
public static void main(String [] args){
Blackjack practice = new Blackjack();
practice.play();
}
}
this one is working.. you have made 2 little mistakes i have commented inside the code. need to wrap while loop content inside {}. and user input needs to be return as string in askUser function. the following code is working as you wanted.
package javaapplication1;
import java.util.*;
public class JavaApplication1 {
private int points;
private int limit;
private Scanner scan;
public JavaApplication1(){
scan = new Scanner(System.in);
}
public void displayPoints(){
System.out.println("Your points:" + points+"/"+limit);
}
/*Purpose: To ask the user for the game limit.
Input: Game limit
Output: Entered limit
*/
public void startGame(){
System.out.println("Enter point limit:");
limit = scan.nextInt();
displayPoints();
}
public int getRoll(){
Random r = new Random();
int roll = r.nextInt(6)+1;
System.out.println("You rolled:" + roll);
return roll;
}
public String askUser(boolean firstTime){
if(firstTime == true)
System.out.println("Start Playing?");
else {
System.out.println("Keep playing?");
}
return scan.next();
}
public void displayResult(){
if(points == limit)
System.out.println("BlackJack!");
else if (points > limit)
System.out.println("Bust!");
else if (points < limit)
System.out.println("Stand at " + points + " points!");
}
public void play(){
boolean gameOver = false;
startGame();
String resUser = askUser(true); // add a variable to catch the input //exp-"yes"
String response = "";
int roll = getRoll();
while(resUser.equals("yes")&& gameOver == false){ // you forget the { and use //the variable to check if it is yess or not
getRoll();
points = points + roll;
displayPoints();
if(points >= limit)
gameOver =true;
else{
resUser = askUser(false);//catching the new user input
}
}// you forget the }. if you are not wrapping the loop with {}, it will only //execute one line after the loop
displayResult();
}
public static void main(String [] args){
JavaApplication1 practice = new JavaApplication1();
practice.play();
}
}

Loop not ending when it's supposed to?

I've been tasked to make a secret word guessing game and it is supposed to be game over and user is asked if they want to play again if the number of guesses for the character reaches 5.
I thought my incrementor is correct but perhaps not...
Here's the class:
public class SecretWord {
private String secretWord;
private String hintWord ;
private int numberOfTurns;
//Default Constructors
public SecretWord()
{
hintWord = "";
secretWord = "juice";
for (int i = 0; i < secretWord.length(); i++)
{
hintWord+="*";
}
this.numberOfTurns = 0;
}
//Accessors
public String getSecretWord()
{
return this.secretWord;
}
public String getHintWord()
{
return this.hintWord;
}
public int getNumberOfTurns()
{
return this.numberOfTurns;
}
//Mutators
public void setSecretWord ()
{
this.secretWord = "juice";
}
public void setHintWord ()
{
//Setting the hint word which sets the asterisks when you guess something right
char[] correctLetters = new char[secretWord.length()];
for (int i = 0; i<secretWord.length();i++)
{
hintWord+="*";
correctLetters[i] += '*';
}
}
public void setNumberOfTurns (int i)
{
this.numberOfTurns = 5;
}
//Methods
public void guessLetter(char guess)
{
String tempHintWord="";
for (int i = 0; i < secretWord.length(); i++)
{
if (secretWord.charAt(i) == guess)
{
tempHintWord += guess;
}
else
{
tempHintWord += hintWord.charAt(i);
}
}
hintWord = tempHintWord;
}
Here's the driver with my loops:
public class SecretWordGame {
//Constant for number of tries
public static final int NUM_TRIES = 5;
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Starts game
boolean quit = false;
while (quit == false)
{
System.out.println("Welcome to the word guessing game! You have " +
+NUM_TRIES+" tries to guess the secret word!");
SecretWord myWord = new SecretWord();
System.out.println("The current hint is \n"+myWord.getHintWord());
while (myWord.getNumberOfTurns() <=NUM_TRIES)
{
System.out.println("Guess a lowercase letter");
//Gets the first letter of what is entered
char tempGuess = keyboard.nextLine().charAt(0);
//Updates the hint by calling guess letter method
myWord.guessLetter(tempGuess);
System.out.println(myWord.getHintWord());
System.out.println("Guess the secret word");
String myGuess = keyboard.nextLine();
//Checks correct guess
if (myGuess.equals(myWord.getSecretWord()))
{
System.out.println("You win!");
break;
}
else
{
System.out.println("Keep trying!");
}
myWord.setNumberOfTurns(myWord.getNumberOfTurns()+1);
}
//Prompts user to play again
System.out.println("Game over! Try again?");
String userInput = keyboard.nextLine();
if(userInput.equalsIgnoreCase("no"))
{
quit = true;
}
else
{
System.out.println("Let's go again!");
}
}
System.out.println("Goodbye!");
}
Maybe the while loop (myWord.getNumberOfTurns() <=NUM_TRIES) comparison is wrong? Or perhaps the getNumberOfTurns incrementor is in the wrong place? I'm unsure.
change
public void setNumberOfTurns (int i)
{
this.numberOfTurns = 5;
}
to
public void setNumberOfTurns (int i)
{
this.numberOfTurns = i;
}
otherwise it would be set to 5 when this code is called myWord.setNumberOfTurns(myWord.getNumberOfTurns()+1);

In my code below Yes/No statement is not functioning properly,

Issue I have is with yes/no statement, if I enter "no" it will continue instead to exit the program.
Please if someone can give me tip where issue is?
import java.util.Random;
import java.util.Scanner;
public class NumberGame {
private static final int DO_NOT_PLAY_AGAIN = 0;
private final Scanner mScanner;
private final Random mRandom;
private String mUserName;
private int mCorrectAnswer;
private int mPlayAgainInput;
private String mAnswer;
public NumberGame() {
mScanner = new Scanner(System.in);
mRandom = new Random();
}
public void run() {
displayWelcomeMessage();
getUserName();
greetUser();
getAnswer();
do {
intNumberGuessGame();
} while (mPlayAgainInput != DO_NOT_PLAY_AGAIN);
sayGoodbye();
}
private void getAnswer(){
System.out.println("Would you lioke to play a game enter yes to play or no to exit a game");
mAnswer = mScanner.nextLine();
if (mAnswer.equals("no"))
System.out.println("Maybe next time");
sayGoodbye();
}
private void displayWelcomeMessage() {
System.out.println("Welcome to the game!");
System.out.println("To play this game you have to"
+ " guess a number and enter upon prompt or you can"
+ " enter 0 to quit the game.");
}
private void getUserName() {
System.out.println("Enter your user name: ");
mUserName = mScanner.nextLine();
}
private void greetUser() {
System.out.println("Let's play a game, " + mUserName + ".");
}
private void sayGoodbye() {
System.out.println("Thanks for playing, " + mUserName + "!");
}
private void intNumberGuessGame() {
// Get a random number between 1 - 100
Random generator = new Random();
mCorrectAnswer = mRandom.nextInt(100) + 1;
int theirGuess = 0;
int howManyTries = 0;
while (theirGuess != mCorrectAnswer) {
System.out.println("Guess my number: ");
theirGuess = mScanner.nextInt();
mCorrectAnswer = mRandom.nextInt(101) + 1;
howManyTries++;
System.out.println("Correct answer = " + mCorrectAnswer);
if (theirGuess == mCorrectAnswer) {
System.out.println("You guessed it! It only took you "
+ howManyTries + " tries to get it right!");
promptToPlayAgain();
// They won the game, exit current loop
break;
} else if (theirGuess > mCorrectAnswer) {
System.out.println("Your answer is too high.");
} else if (theirGuess < mCorrectAnswer) {
System.out.println("Your answer is too low.");
}
}
}
private void promptToPlayAgain() {
System.out.println("Do you want to play again? (0 to quit): ");
mPlayAgainInput = mScanner.nextInt();
}
}
public class MainApp {
public static void main(String[] args) {
new NumberGame().run();
}
}
Your logic seems a little bit messy right now. I would advise you to redesign your code a little bit. Your problem lies in how getAnswer() function is designed - it prompts for answer, but does not use it. Change this function so it can return a boolean value:
private boolean getAnswer()
{
System.out.println("Would you lioke to play a game enter yes to play or no to exit a game");
mAnswer = mScanner.nextLine();
if (mAnswer.equals("no"))
{
System.out.println("Maybe next time");
sayGoodbye();
return false;
}
return true;
}
Use this result in run() to check if game should be started at all:
public void run()
{
displayWelcomeMessage();
getUserName();
greetUser();
if(getAnswer()) //User wants to play!
{
do
{
intNumberGuessGame();
} while (mPlayAgainInput != DO_NOT_PLAY_AGAIN);
sayGoodbye();
}
}
First of all, when you're checking if mAnswer is equal to "no", you're only printing one string and you always execute the sayGoodbye because you're missing braces. It should be:
if (mAnswer.equals("no")) {
System.out.println("Maybe next time");
sayGoodbye();
}
Second of all, if you want the yes/no question to decide whether or not you continue playing, you will need to either check
do {
intNumberGuessGame();
} while (mPlayAgainInput != DO_NOT_PLAY_AGAIN || !mAnswer.equals("no"));
or set the mPlayAgainInput value to 0 in the getAnswer() function, precisely in the braces i pointed out earlier. If you choose this option, you should change to do-while block to a regular while block.
Because when the user inputs "no" you simply print a message and never actually tell the program to exit.
You can adjust it in many different ways, for example change the getAnswer method to:
private int getAnswer() {
System.out.println("Would you like to play a game? Enter yes to play or no to exit a game");
mAnswer = mScanner.nextLine();
if (mAnswer.equals("no")) {
System.out.println("Maybe next time");
return DO_NOT_PLAY_AGAIN;
} else {
return 1;
}
}
And your run method to:
public void run() {
displayWelcomeMessage();
getUserName();
greetUser();
mPlayAgainInput = getAnswer();
while (mPlayAgainInput != DO_NOT_PLAY_AGAIN) {
intNumberGuessGame();
}
sayGoodbye();
}

Java SecretWord Code

I am making basic java program to hold a secret word (mouse) and allow a user to guess letters. The program will end either when the user guesses all the letters in the word, or when they guess 7 wrong letters. Whenever I type any letter into the program, it will run through it without giving the user an option to enter another letter. What should I add so that it will only run the program once per letter entered? Also if it wasnt quite obvious I am new to coding.
import java.util.Scanner;
public class GuessWord
{
String Secretword="mouse";
String letter;
int index;
private int number;
private int counter;
private String guesses;
Scanner scan = new Scanner(System.in);
public GuessWord()
{
String Secretword="";
String letter = "";
String guesses = "";
int number = 0;
int counter = 0;
int index = 0;
}
public String getLetter(){
System.out.println("Please enter a letter");
letter = scan.next();
return letter;
}
public void calc(){
guesses=letter;
while(number <= 7 && counter<5)
{
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
guesses=guesses+" " +letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if(number == 7){
System.out.println("You lose");
}else
{
System.out.println("You win");
}
}
}//class
public class GuessWordR
{
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
g1.getLetter();
g1.calc();
}//class
}//main
You should use a while loop.
So while some condition is not met keep asking the user to enter a new key.
Perhaps add a new method to the GuessWord Class
public void startGuessing() {
while(hasGuesses /* some boolean flag */) {
getLetter()
getCalc()
}
}
And then call that method in your main method instead of getLetter() and getCalc().
You will need to add a boolean variable to your class to indicate when to exit this while loop and the logic to keep count of the number of failed guesses etc.
Use a boolean flag and run it in a loop. but for that you need to restructure your code as well. First fix the calc() method
public boolean calc() {
guesses = letter;
if (number <= 7 && counter < 5) {
if (Secretword.indexOf(letter) != -1) {
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
} else {
System.out.println("You entered an incorrect letter");
number++;
}
guesses = guesses + " " + letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if (number == 7) {
System.out.println("You lose");
return true;
} else if (counter == 5) {
System.out.println("You win");
return true;
} else {
return false;
}
}
Your main method should be update like this
public static void main(String[] args) {
GuessWord g1 = new GuessWord();
boolean completed = false;
while (!completed) {
g1.letter = g1.getLetter();
completed = g1.calc();
}
}
you ask user for input unless condition get satisfied instead of asking and calculating once. And read char by char input instead of reading whole string.
something like:
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
while(number <= 7 && counter<5){
g1.getLetter();
g1.calc();
}
}//class

Boolean bug (FibonacciNumbers)

First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.

Categories