I have to create a hangman game. I am stuck in the last step. In fact, when the user finds the word my input asks yet a letter.
Here an example: (the word to find is "non")
Enter your letter please : n
n _ n
Enter your letter please : o
n o n
Enter your letter please :
n o n
My problem is probably my wordFind, I don't understand how to manipulate this ?
String[] words = {"yess", "non"};
String wordRandom = words[(int) (Math.random() * words.length)];
boolean[] letterGuess = new boolean [wordRandom.length()];
boolean wordFind = false;
int numberAttempt = 5;
while(numberAttempt > 0 && !wordFind){
System.out.println("Number of attempt(s) " + numberAttempt);
for(int i=0; i < wordRandom.length(); i++){
if(letterGuess[i]){
System.out.print(wordRandom.charAt(i));
}
else{
System.out.print("- ");
}
}
System.out.println(" ");
System.out.print("Enter your letter please : ");
char letter = input.next().charAt(0);
int letterFound = 0;
boolean alreadyFound = false;
for(int i=0; i < wordRandom.length(); i++){
if(wordRandom.charAt(i) == letter){
if(letterGuess[i]){
alreadyFound = true;
}
letterGuess[i] = true;
letterFound++;
}
}
if(alreadyFound){
System.out.println("Letter already proposed and it has been found ! ");
} else{
if(letterFound == 1){
System.out.println("The letter is correct ! ");
}
else if(letterFound > 0){
System.out.println("The letter is " + letterFound + " times in the word ! ");
}
else{
numberAttempt--;
System.out.println("The letter is not in the word ! ");
}
}
}
You need to add a solved condition like this
boolean wordFind = false;
int numberAttempt = 5;
boolean solved = false;
while(numberAttempt > 0 && !wordFind && !solved){
after you update letterFound, set solved
letterFound++;
if (letterfound == wordRandom.length()) {
solved = true
}
Then at the end after the while loop, if solved is true, congratulate the user.
You can create a variable int amountCorrect = 0; and use that as a check. Every time the user gets a right letter, add to amountCorrect the number of letters there are. At the beginning of the while loop, create a boolean check that checks if the amountCorrect variable is the same as the length of the wordRandom. I know your code is kind of long, so I put a comment next to the lines where I added code:
String[] words = { "yess", "non" };
String wordRandom = words[(int) (Math.random() * words.length)];
boolean[] letterGuess = new boolean[wordRandom.length()];
boolean wordFind = false;
int numberAttempt = 5;
int amountCorrect = 0; // The amountCorrect variable
while (numberAttempt > 0 && !wordFind) {
System.out.println("Number of attempt(s) " + numberAttempt);
// This is the boolean check
if (amountCorrect == wordRandom.length()) {
System.out.println("You Win!");
break;
}
for (int i = 0; i < wordRandom.length(); i++) {
if (letterGuess[i]) {
System.out.print(wordRandom.charAt(i));
} else {
System.out.print("- ");
}
}
System.out.println(" ");
System.out.print("Enter your letter please : ");
char letter = input.next().charAt(0);
int letterFound = 0;
boolean alreadyFound = false;
for (int i = 0; i < wordRandom.length(); i++) {
if (wordRandom.charAt(i) == letter) {
if (letterGuess[i]) {
alreadyFound = true;
}
letterGuess[i] = true;
letterFound++;
// add to amountCorrect
amountCorrect++;
}
}
if (alreadyFound) {
System.out.println("Letter already proposed and it has been found ! ");
} else {
if (letterFound == 1) {
System.out.println("The letter is correct ! ");
}
else if (letterFound > 0) {
System.out.println("The letter is " + letterFound + " times in the word ! ");
}
else {
numberAttempt--;
System.out.println("The letter is not in the word ! ");
}
}
}
Related
package Demo;
import java.util.Scanner;
public class seat_reservation{
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
// Initialization
final int ROWS = 2;
final int COLS = 3;
char [][] seats = new char [ROWS][COLS];
int i, j, seatNum, counter = 0;
char seatLetter = 'A';
int choice = 0;
String seatEnter;
boolean cont = true; // loops of running the program
while( choice != 4 ){
System.out.print( "1. Assign Seats" );
System.out.print( "2. Exit" );
System.out.print( "Select your choice: " );
choice = read.nextInt();
switch( choice ){
case 1:
//Set the value.
for (i=0; i < seats.length; i++) {
for (j=0; j < seats[i].length; j++)
seats[i][j] = seatLetter++;
seatLetter = 'A'; // to reset the value to A for the new loop
}
//To display the list of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j]+" ");
System.out.println();
}
//condition
while (counter < 6 && cont) {
do {
System.out.print("Please type the chosen seat(starts with row and column,e.g:2A):" + "");
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0)+"");
if (seatNum != 0)
seatLetter = seatEnter.charAt(1);
i++;
//if user enters wrong input, error message will appear.
if (seatLetter!='A'){
if (seatLetter!='B'){
if(seatLetter!='C'){
if(seatLetter!='D')
System.out.println ("Invalid! Please enter the correct seat:");
}
}
}
}
//continue to loop until the condition true
while (seatNum < 0 || seatNum > 7 || seatLetter < 'A' || seatLetter > 'D');
if (seatNum == 0) {
cont = false;
} else {
if (seats[seatNum-1][seatLetter-65] == 'X')
System.out.println("Seat have been taken.Please choose another seat:");
else {
seats[seatNum -1][seatLetter-65] = 'X';
counter++;
}
// To display updated lists of seats
for (i=0; i < seats.length; i++) {
System.out.print((i+1)+" ");
for (j=0; j < seats[i].length; j++)
System.out.print(seats[i][j] + " ");
System.out.println();
}
System.out.println(" ") ;
//}
//}
// displays fully booked message
if (counter == 6)
System.out.println("All seats are now fully-booked.");
break;
}
}
case 2://syntax error here
if (counter == 6)
System.out.println( "All seats are now fully-booked." );
System.out.println( "End of Program" );
System.exit(0);
break;
default:
System.out.println("Error input");
break;//syntax error here as well.
}
}
}
}
The problem is caused due to:
choice = read.nextInt();
The scanner.nextInt() only takes the next token from the input. Rest are ignored by it.
So when you're trying to take the next input from this line and process it, the error occurs:
seatEnter = (read.nextLine()).toUpperCase(); //covert to Upper case
seatNum = Integer.parseInt(seatEnter.charAt(0) + "");
As the previous read.nextInt() left the rest except first token, when you hit enter after giving 1 as input, it took only the 1 and the enter or newline token was captured by the read.nextLine(). That is why it got no charAt(0) and thus thrown StringIndexOutOfBoundException.
Try:
choice = Integer.parseInt(read.nextLine());
or,
choice = read.nextInt();
read.nextLine(); // this will capture the residue
I am making a movie guessing game(much like hangman but doesn't contain the stick figure and stuff) on Java that takes input from the user, letter by letter. I am stuck where I want the letter entered to replace all instances of that letter in the title of the movie. My code is not working completely.
Later, I am gonna apply the logic that stops the user from entering the same letter again. But at the moment I need to fix this particular issue. Any help?
This is the game process function in my game class.
public void GameProcess(char[] dashedarray) {
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
while (run) {
if (dashedarray[i] == ' ') {
spaces++;
i++;
continue;
} else {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if (moviename.charAt(i) == guess) {
dashedarray[i] = guess;
correct++;
}
else if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
}
}
else
{
wrong++;
}
}
i++;
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}
}
You don't need i at all. spaces is to count the number of spaces in your answer, which does not need to be guessed. You should do that outside of the loop.
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
for (int i = 0; i < dashedarray.length; i++) {
spaces++;
}
while (run) {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
boolean match = false;
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
match = true;
}
}
}
// It matched nothing, this input is wrong.
if (!match) {
wrong++;
}
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int guesses = 0;
//Do I really need this part?
//Ask the user to enter a word and store it into an array
System.out.println("Please enter a word: ");
String wordToGuess = kybd.next();
char[] word = wordToGuess.toCharArray();
char[] underscore = new char[wordToGuess.length()];
for (int i = 0; i < wordToGuess.length(); i++) {
underscore[i] = '_';
}
System.out.println("You have 6 tries to guess the word:");
for ( int i = 0; i < wordToGuess.length(); i++) {
System.out.println(" " + underscore[i] + " ");
}
System.out.println("Please enter your guess: ");
char guess = kybd.next();
for (int i = 0; i < word.length; i++) {
if (guess == word[i]) {
underscore[i] = guess;
}
}
}
}
// I've gotten a little lost here.
I know this is not right at all but I'm hoping for some tips. Thanks so much!!
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner kybd = new Scanner(System.in);
System.out.println("Please enter a word: ");
String wordToGuess = kybd.next();
char[] underscore = new char[wordToGuess.length()];
for (int i = 0; i < wordToGuess.length(); i++) {
underscore[i] = '_';
}
int wordLenToGuess = wordToGuess.length();
int unsuccessfulTries = 6;
while(wordLenToGuess >0 && unsuccessfulTries >0 ){
System.out.println();
for ( int i = 0; i < wordToGuess.length(); i++) {
System.out.print(" " + underscore[i] + " ");
}
System.out.println();
System.out.println("You have " +unsuccessfulTries+ " tries to make a guess");
System.out.println("Please enter your guess: ");
//kybd.nextLine();
char guess = kybd.next().charAt(0);
boolean iscorrect = false;
for (int i = 0; i < underscore.length; i++) {
if(wordToGuess.charAt(i) == guess)
{
underscore[i] = guess;
wordLenToGuess--;
iscorrect = true;
}
}
if(!iscorrect)
unsuccessfulTries--;
}
if(wordLenToGuess == 0)
System.out.println("YOU WIN!! :)");
else System.out.println("Sorry! You Lose :(");
}
}
Algorithm:
Keep trying till either entire word is guessed or 6 incorrect tries.
If correct letter is guessed, fill in the blanks '_' else decrement the number of tries
Exit loop when either entire word is guessed or all 6 tries are used up.
Inform user if he wins or loses.
Couple things that need to be addressed here include giving the user the option to guess either a letter or a word, having the game go on as long as the user has not yet guessed the word yet, and checking to see if the user guessed a letter he or she has already guessed (this last thing is optional but is good practice for error checking). Think about the condition that will keep the game going. The game won't end until the user guessed 6 times or managed to successfully guess the word. To check these conditions after each guess, we can use a while loop. To see if the user guessed the word correctly, we can use a boolean variable to keep track of this,
boolean wordHasBeenGuessed = false;
while(!wordHasBeenGuessed && guesses < 6)
//this loop reads "while the word has not been guessed yet and the user has not exceeded 6 guesses
To give the user the option to guess either a letter or a word, we need to present two scenarios using if statements,
System.out.println("Would you like to guess a letter or a word?");
String type = kybd.next();
if(type.toLowerCase().equals("letter"){
//do stuff to deal with this case here
}
else{
//do stuff to deal with this case here
}//of course this part can be customized anyway you'd like
In the end, it should look something like this,
import java.util.Scanner;
public class HangmanGame {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int guesses = 0;
//Ask the user to enter a word and store it into an array
System.out.println("Please enter a word: ");
String wordToGuess = kybd.next();
char[] word = wordToGuess.toCharArray();
char[] underscore = new char[wordToGuess.length()];
for (int i = 0; i < wordToGuess.length(); i++) {
underscore[i] = '_';
}
boolean wordHasBeenGuessed = false;
int numOfLettersFound = 0;
while(!wordHasBeenGuessed && guesses < 6){
System.out.println("You have " + (6-guesses) + " tries to guess the word:");
for ( int i = 0; i < wordToGuess.length(); i++) {
System.out.print(" " + underscore[i] + " ");
}
System.out.println("Would you like to guess a letter or a word?");
String type = kybd.next();
if(type.toLowerCase().equals(letter)){
System.out.println("Enter your guess");
char guess = kybd.next();
for (int i = 0; i < word.length; i++) {
if (guess == word[i]) {
underscore[i] = guess;
numOfLettersFound++;
}
}
if(numOfLettersFound == wordToGuess.length()){
wordHasBeenGuessed = true;
}
}
else{
System.out.println("Enter your guess");
String answer = kybd.next();
if(answer.eqauls(wordToGuess){
wordHasBeenGuessed = true;
}
}
guesses++;
}
//after the while loop is finished, tell the user whether or not he/she has won or not
if(wordHasBeenGuessed){
System.out.println("You won");
}
else{
System.out.println("You lost");
}
}
}
If you have any questions, feel free to ask.
I have code that first generates the array with 100 elements, then places randomly generated numbers in each element. I am trying to do a search for a number and if found, print out its index. the code I have so far is:
import java.util.Scanner;
public class Lab01
{
public static void main(String[] args)
{
int[] nums = new int[100];
for (int i = 0; i < nums.length; i++)
{
nums[i] = (int)((Math.random() * 100) + 1);
System.out.print(nums[i] + " , ");
}
System.out.println();
Scanner input = new Scanner(System.in);
int num;
System.out.println("What number would you like to search for?");
num = input.nextInt();
boolean found = false;
for (int i = 0; i < nums.length; i++)
{
if (num == nums[i])
{
found = true;
break;
}
if (found)
{
System.out.println("That number was found at index" + i);
break;
}
else
{
System.out.println("That number was not found.");
break;
}
}
}
}
I put in the print statements to see the values, so I could verify that it was working, but it ALWAYS returns "Not found". What am I missing here?
Try to replace this block, see the explanation in the bottom :
for (int i = 0; i < nums.length; i++)
{
if (num == nums[i])
{
found = true;
break;
}
if (found)
{
System.out.println("That number was found at index" + i);
break;
}
else
{
System.out.println("That number was not found.");
break;
}
With:
int i; // create this
for ( i = 0; i < nums.length; i++) // and remove int from for loop
{
if (num == nums[i])
{
found = true;
break;
}
}
if (found)
{
System.out.println("That number was found at index " + i);
}
else
{
System.out.println("That number was not found.");
}
Explanation:
Put out of for loop the both if condtion and remove the break statement from them and create a int i = 0 before the for loop like above.
You are breaking out of the loop after checking the first number, so if the first number doesn't match, you print "That number was not found". If the first number does match, you break without printing anything. You should only print "That number was not found" after checking all the numbers of the array.
Your if statement should come after the for loop, not inside it.
int i = 0;
for (; i < nums.length; i++) {
if (num == nums[i]) {
found = true;
break;
}
}
if (found) {
System.out.println("That number was found at index" + i);
} else {
System.out.println("That number was not found.");
}
Try this :)
public static void main(String[] args) {
int[] tab = {3, 2, 1, 7, 2, 1};
int userInput, i;
Integer index = null;
boolean found = false;
int counter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
userInput = input.nextInt();
for (i = 0; i<tab.length; i++) {
if (tab[i] == userInput) {
found = true;
index = i;
counter++;
}
}
if (found == true) {
System.out.println("Found number: " + userInput + " at index " + index + " and number is found " + counter + " times in array");
} else {
System.out.println("Not found number: " + userInput);
}
}
public class Contains {
public static void main(String[] args) {
int[] num = {1, 2, 3, 4, 5};
int toFind = 3;
boolean found = false;
for (int n : num) {
if (n == toFind) {
found = true;
break;
}
}
if(found)
System.out.println(toFind + " is found.");
else
System.out.println(toFind + " is not found.");
}
}
import java.util.*;
public class HangManP5
{
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(System.in);
System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game!\n");
RandomWord(word);
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
String test = k.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
int foundPos = -2;
int foundCount = 0;
while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
len--;
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println("\n---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println("\n---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was \"" + word + "\"");
}
}
public static String RandomWord(String word)
{
//List of words
Random r = new Random();
int a = 1 + r.nextInt(5);
if(a == 1)
{
word=("Peace");
}
if(a == 2)
{
word=("Nuts");
}
if(a == 3)
{
word=("Cool");
}
if(a == 4)
{
word=("Fizz");
}
if(a == 5)
{
word=("Awesome");
}
return (word);
}
}
Ok, so this is my code for a hangman game, the only thing I have left to do is to get my program to randomize one of the words, which it should do in the method successfully. But the only problem I'm having is getting the String variable "word" to go back to the main class (there are errors underlining all the "word" variables in the main class).
If I could get help with either this or another way to produce a random word from a list, that would be amazing.
In java, parameters are passed by value and not by reference. Therefore, you cannot change the reference of a parameter.
In your case, you need to do:
public static String getRandomWord() {
switch(new Random().nextInt(5)) {
case 0:
return "Peace";
case 1:
return "Nuts";
// ...
default:
throw new IllegalStateException("Something went wrong!");
}
}
And in main:
// ...
String word = getRandomWord();
int len = word.length();
// ...
You can't modify the caller's reference.
RandomWord(word);
needs to be something like
word = RandomWord(word);
Also, by convention, Java methods start with a lower case letter. And, you could return the word without passing one in as an argument and I suggest you save your Random reference and use an array like
private static Random rand = new Random();
public static String randomWord() {
String[] words = { "Peace", "Nuts", "Cool", "Fizz", "Awesome" };
return words[rand.nextInt(words.length)];
}
And then call it like
word = randomWord();