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
Related
Hi I am creating a mock atm, and I created a method to check if the user's pin is inputted wrong, but if it is wrong it spams incorrect pin 3 times then my program stops, I am looking at how to have the user input incorrectly have it tell them it is wrong once then have them retry their pin until they reach the max 3 attempts.
My while loop is with my ATM class (First time posting bare with me)
MAIN
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner enterPin = new Scanner(System.in);
System.out.println("Enter your 4 digit pin: ");
String userPin = enterPin.nextLine();
ATM pin = new ATM("1234");
pin.checkPin(userPin);
}
}
ATM CLASS
public class ATM {
String pin;
int counter;
public ATM(String pin){ //constructor 1 for pin
this.pin = pin;
}
public ATM(int counter){ //constructor for counting how many times pin is entered
this.counter = counter;
}
public String getPin(){
return pin;
}
public boolean setPin(String pin){
this.pin = pin;
return true;
}
public boolean checkPin(String userPin){
while(!userPin.contains(pin) && counter < 3) {
System.out.println("Incorrect pin.");
counter += 1;
if (counter >= 3){
System.out.println("Incorrect pin your account has been blocked.");
return false;
}
}
if(userPin.contains(pin)){
System.out.println("Your pin is correct!");
}
return true;
}
}
I don't see any user input in your code (i.e no Scanner to take in user input), so what's happening is userPin stays the same throughout each loop.
[userPin is false --> count++ --> print "Incorrect pin"] repeats 3 times, that's why it spams 3 times.
Here's the code I've rewritten:
public boolean checkPin() {
int counter = 0;
Scanner scanner = new Scanner(System.in);
while(counter < 3) {
String userPin = scanner.nextLine();
if(userPin.contains(pin)){
System.out.println("Your pin is correct!");
return true;
}
System.out.println("Incorrect pin.");
counter += 1;
}
System.out.println("Too many tries, your account has been blocked.");
return false;
}
I am trying to figure out where to put the loop that when the user enters any value other than "rock", "paper" or "scissors" the program stays in the loop and displays "Invalid entry" while requesting the user to enter again.
Any help is much appreciated.
As it stands now, the program will display "Invalid entry" but then continues without asking the user to try again.
import java.util.Scanner; // Import the Scanner class
import java.util.Random; // Import the random class for game
/**
*/
public class Challenge17
{
// Method to determine the random choice of computer
public static String getComputerChoice(Random random)
{
int number;
number = random.nextInt(3) + 1;
String computerChoice;
switch (number)
{
case 1:
computerChoice = "rock";
break;
case 2:
computerChoice = "paper";
break;
case 3:
computerChoice = "scissors";
break;
default:
computerChoice = "";
}
return computerChoice;
}
// Method to display the menu for choices
public static void displayChoice( )
{
System.out.println("Game Options\n----------\n"
+ "1: rock\n2: paper\n3: scissors");
}
// Method to request and hold user choice for game
public static String getUserInput(Scanner keyboard)
{
String userInput;
System.out.println("Enter your choice: ");
userInput = keyboard.nextLine();
return userInput;
}
// Method to determine winner
public static String determineWinner(String computerChoice, String userInput)
{
String winner = "Tie Game!"; // Default display Tie game
String message = ""; // To determine the message for winner
String displayMessage; // To display the message for winner
// Custom messages below
String rockMessage = "Rock smashes scissors";
String scissorsMessage = "Scissors cuts paper";
String paperMessage = "Paper wraps rock";
boolean loop = false;
if(computerChoice.equals("rock") && userInput.equalsIgnoreCase("scissors"))
{
winner = " Computer wins!";
message = rockMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("rock") && computerChoice.equals("scissors"))
{
winner = "You win!";
message = rockMessage;
loop = true;
}
if(computerChoice.equals("scissors") && userInput.equalsIgnoreCase("paper"))
{
winner = " Computer wins!";
message = scissorsMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("scissors") && computerChoice.equals("paper"))
{
winner = "You win!";
message = scissorsMessage;
loop = true;
}
if(computerChoice.equals("paper") && userInput.equalsIgnoreCase("rock"))
{
winner = " Computer wins!";
message = paperMessage;
loop = true;
}
else if (userInput.equalsIgnoreCase("rock") && computerChoice.equals("scissors"))
{
winner = "You win!";
message = paperMessage;
loop = true;
}
else
{
System.out.println("Invalid entry.");
loop = false;
}
displayMessage = winner + " " + message;
return displayMessage;
}
// Main method to initiate and execute game
public static void main(String[] args)
{
Random random = new Random(); // To call the random class
Scanner keyboard = new Scanner(System.in); // To call the scanner class
String computerChoice; // Hold computer input
String userInput; // Hold user input
String input; // Hold input for repeat
char repeat; // Character for repeat
do
{
displayChoice(); // Call method to display the choices
computerChoice = getComputerChoice(random); // Hold the PC random choice
userInput = getUserInput(keyboard); // To get the user input
System.out.println("You chose: " + userInput + " computer chose: \n"
+ computerChoice);
System.out.println(determineWinner(computerChoice, userInput));
// Does the user want to play again
System.out.println("Would you like to play again?");
System.out.print("Enter Y for yes, or N for no: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
while (repeat == 'Y' || repeat == 'y');
}
}
From my understanding i'm pretty sure you want this kind of a loop
public static String getUserInput(Scanner keyboard)
{
String userInput;
System.out.println("Enter your choice: ");
userInput = keyboard.nextLine();
while(!userInput.equals("rock")&&!userInput.equals("paper")&&!userInput.equals("scissors"))
{
System.out.println("Invalid Entry, Please re-enter your choice:");
userInput = keyboard.nextLine();
} //It wont go out of the loop unless it's one of the 3 choices
return userInput;
}
You could create a Boolean method.
private Boolean checkUserInput(String input) {
if(!input.equalsIgnoreCase("rock") && !input.equalsIgnoreCase("paper") && !input.equalsIgnoreCase("scissors")) return false;
return true;
Then you do the check before you determine the winner like if true then run the determineWinner(computerChoice, userInput) code else it doesn't.
That way, you can edit the code and add functionalities in the future if need be.
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 : ");
}
Hi Guys Getting this error "Error: Could not find or load main class Hangman.java" when i try to run the file.It compiles fine.Could you please advise what is missing. This a hangman game with the following attributes
-the secret word
-the disguised word, in which each unknown letter in the secret word is replaced wit a question mark (?). For example, if the secret word is "abracadabra" and the letters a,b, and e have been guessed, the disguised word would be ab?a?a?ab?a.
-the number of guess made
-the number of incorrect guesses
It will have the following methods:
-makeGuess (c) guesses that character c is in the word
-getDisguisedWord returns a string containing correctly guessed letters in their correct positions and unknown letters replaced with "?"
-getSecretWord returns the secret word
-getGuessCount returns the number of guesses made
-isFound returns true if the hidden word has been discovered
import java.util.*;
public class Hangman {
private String secretWord;
private String disguisedWord ="";
private String guessedLetters = "";
private int numberOfGuesses = 0;
private int numberOfIncorrectGuesses = 0;
Hangman(String secretWord){
this.secretWord = secretWord;
for (int i = 0; i < secretWord.length(); i++){
this.disguisedWord += "?";
}
}
public String getSecretWord() {
return secretWord;
}
public String getGuesses() {
return guessedLetters;
}
public String getDisguisedWord() {
return disguisedWord;
}
public int getGuessCount() {
return numberOfGuesses;
}
public int getIncorrectGuessCount() {
return numberOfIncorrectGuesses;
}
public boolean isFound() {
if (secretWord.equalsIgnoreCase(disguisedWord)){
return true;
} else{
return false;
}
}
public boolean makeGuess(char guess) {
for (int i = 0; i < guessedLetters.length(); i++){
if (guess == guessedLetters.charAt(i)) {
System.out.println("You have already guessed that letter.");
return false;
}
}
guessedLetters+= guess;
String tempString = "";
numberOfGuesses++;
for (int i = 0; i < secretWord.length(); i++) {
if (guess == secretWord.charAt(i)){
tempString += guess;
} else {
tempString += disguisedWord.charAt(i);
}
}
if (!tempString.equalsIgnoreCase(disguisedWord)) {
disguisedWord = tempString;
return true;
} else {
System.out.println("Incorrect Guess!");
numberOfIncorrectGuesses++;
return false;
}
}
public static void main(String[] args) {
java.util.Scanner keyboard = new java.util.Scanner(System.in);
Hangman hangman = new Hangman("pirate"); // enter secret word as a string
while (hangman.isFound()== false){
System.out.println("The word is: " + hangman.getDisguisedWord());
System.out.println("Guess a letter or type 'guesses' to see your guesses.");
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("guesses"))
{
System.out.println(hangman.getGuesses());
}
else
{
hangman.makeGuess(input.charAt(0));
}
}
System.out.println("The secret word was: " + hangman.getSecretWord());
System.out.println("It took you " + hangman.getGuessCount() + " guesses to get the correct answer.");
System.out.println("You had " + hangman.getIncorrectGuessCount()+ " incorrect guesses.");
}
}
You should run the program using :
java -cp . Hangman
and not
java Hangman.java
The important thing to understand here is that
You compile java classes using javac <classname>.java
You run java programs using java <classname> (Notice that there is no .java required while running the program)
In this program i needed the user to input yes / no to be set in another array class. But the string input doesnt work. I tried it with an integer and it worked but not with a string.
package airliner.boarding.system;
import java.util.Scanner;
public class BoardPlane {
private boolean firstClass[];
private boolean economyClass[];
private static Scanner input ;
public BoardPlane(){
firstClass = new boolean[5];
economyClass = new boolean[5];
input = new Scanner(System.in);
}
public void setSeat(int seatClass){
if(seatClass == 1){
fillFirstClass();
}else if(seatClass == 2){
fillEconomyClass();
}
}
private void fillEconomyClass(){
for(int counter = 0; counter < economyClass.length; counter++){
if(economyClass[counter] == false){
economyClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the economy class");
break;
}else if(counter == 4){
System.out.println("Economy class is filled. is it okay to place you in first class? YES/NO: ");
String choice = input.nextLine();
choice = choice.toUpperCase();
if(choice.equals("YES")){
switchSeats(2);
}else{
System.out.println("Next flight leaves in three hours.");
}
}
}
}
private void fillFirstClass(){
for(int counter = 0; counter < firstClass.length; counter++){
if(firstClass[counter] == false){
firstClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the first class");
break;
}else if(counter == 4 ){
System.out.println("First class is filled. is it okay to place you in economy class? YES/NO:");
String choice = input.nextLine();
choice = choice.toUpperCase();
if(choice.equals("YES")){
switchSeats(1);
}else{
System.out.println("Next flight leaves in three hours.");
}
}
}
}
private void switchSeats(int i){
if(i == 1){
for(int counter = 0; counter < economyClass.length; counter++){
if(economyClass[counter] == false){
economyClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the economy class");
break;
}else if(counter == 4){
System.out.println("Economy class is filled");
}
}
}else if(i == 2){
for(int counter = 0; counter < firstClass.length; counter++){
if(firstClass[counter] == false){
firstClass[counter] = true;
System.out.println("Your seat number is "+(++counter)+" in the first class");
break;
}else if(counter == 4){
System.out.println("First class is filled");
}
}
}
}
public static void main(String [] args){
BoardPlane plane = new BoardPlane();
for(int i = 0; i <= 10; i++){
System.out.println("Enter 1 for first class and 2 for economy class: ");
int userInput = input.nextInt();
plane.setSeat(userInput);
}
}
}
When you call nextInt() it only reads the number, not the rest of the line and not the new line you typed.
This means if you later call nextLine() it will read what ever was after the number i.e. most likely nothing.
A simple work around is to ignore the rest of the line after the number.
int userInput = input.nextInt();
input.nextLine(); // ignore the rest of the line.
i have same problem, when you use scanner, and put the message with System.out.println(), newLine not work correctly.I dont know why ?! when you make input = new Scanner(System.in) after out your message in console, it's work correct.
but u can make a method for give user input and in this method make a feresh scanner like this :
publis static String getUserInput(String message){
System.out.println(message);
input = new Scanner(System.in);
return input.nextLine();
}