Repeated letters logic not working in java - java

I am working on a version of hangman, and I need to include a condition that checks if a letter guess was already used. My repeated letters if statement is not working correctly. Any advice?
NOT FULL CODE. ONLY A PIECE IS SHOWN
char[] repeatedLetters = new char[26];
int incorrect = 0;
while (incorrect < 7)
{
System.out.println("\nGuess a letter: ");
char guess = kb.next().toUpperCase().charAt(0); // case insensitive
for (int i = 0; i < repeatedLetters.length; i++)
{
if (repeatedLetters[i] == guess) {
System.out.println("You already guessed " + guess + ".");
System.out.println("Guess a letter: ");
guess = kb.next().toUpperCase().charAt(0);
}
else
repeatedLetters[i] = guess;
}

Personally, I would suggest using a List instead of array.
List<Character> repeatedLetters = new ArrayList<>();
int incorrect = 0;
while (incorrect < 7)
{
System.out.println("\nGuess a letter: ");
char guess = kb.next().toUpperCase().charAt(0); // case insensitive
if (validateCharacter(guess) && repeatedLetters.contains(guess)) {
System.out.println("You already guessed " + guess + ".");
continue;
}
else {
repeatedLetters.add(guess);
}
// Other things
}
If you are not allowed to use a list, then you need to move the else block outside of the for loop, use a labelled while loop, and also manually count the number of repeated characters.
int repeatedCount = 0;
getInput : while (incorrect < 7) {
// ......
for (int i = 0; i < repeatedCount; i++) {
if (repeatedLetters[i] == guess) {
System.out.println("You already guessed " + guess + ".");
continue getInput;
}
}
repeatedLetters[repeatedCount] = guess;
repeatedCount++;

Related

how to extract answers from for loop

I can't figure out how to correctly write my for loop statement that will give me the correct score. I bolded the code that is what I can't figure out how to write correctly. Anytime I run my program I end up with the first result of (rslt < 3) no matter what numbers I enter.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String options[] = {
"mild or spicy",
"tea or coffee",
"breakfast or " +
"brunch",
"summer or winter",
"paper or plastic"
};
int answers[] = new int[options.length];
String result[] = new String[answers.length];
boolean bool = true;
while (true) {
for (int i = 0; i < options.length; i++) {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 1] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 2] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 3] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 4] + "?");
answers[i] = scanner.nextInt();
break;
}
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
int rslt = getScore(result);
if (rslt < 3)
System.out.println("You prefer life to be calm and organized");
else if (rslt > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
int out = scanner.nextInt();
if (out == 0)
bool = false;
if (!bool)
System.exit(0);
}
}
static int getScore(String[] result) {
int score = 0;
for (int i = 0; i < result.length; i++) {
switch (result[i]) {
case "spicy":
score++;
break;
case "coffee":
score++;
break;
case "breakfast":
score++;
break;
case "winter":
score++;
break;
case "paper":
score++;
break;
}
}
return score;
}
}
I have modified your code according to my understanding of the code.
It works just exactly like you may have wanted.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[][] options = {
{"mild", "spicy"},
{"tea", "coffee"},
{"brunch", "breakfast"},
{"summer", "winter"},
{"plastic", "paper"}
};
int[] answers = new int[options.length];
do {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i][0] +
" or " + options[i][1] + "?");
answers[i] = scanner.nextInt();
}
int result = getScore(answers);
if (result < 3)
System.out.println("You prefer life to be calm and organized");
else if (result > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
} while (scanner.nextInt() != 0);
}
static int getScore(int[] answers) {
int score = 0;
for (int answer : answers) if (answer == 1) score++;
return score;
}
}
To Fix Your Code
In the first for-loop, you are supposed to loop through the options array. But somehow you unfold the loop within the loop body. To prevent the whole thing loop again, you break the loop immediately. To fix the first loop, write it like this instead. Properly loop through each element, no need to unfold it, no need to break it.
System.out.println("Enter 0 for the preference on the left\n" + "Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
}
In the second loop, you are supposed to retrieve the selected string from answers and write the string to results. Without modifying your data structure, this can be achieved by using split(" or ") on the option, which gives you an array of string which you can use the answer as index to access. Note that this does not prevent array index out of bound exception if user enter anything other than 0 or 1, which you should totally do, but is out of scope of this question.
for (int i = 0; i < answers.length; i++) {
result[i] = options[i].split(" or ")[answers[i]] ;
}
And there you go.
To Solve Your Task
Alternatively, redesigning the data structure and logic to get rid of the unnecessary string manipulation and comparison is more ideal. You don't even need the result and answers array, simply add up the user input will do (if the user follows your instruction)
int rslt = 0;
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
rslt += scanner.nextInt();
}
Inside the loop, you continue assigning the result to the same index in the answers list, rather than assigning the result to another index for each input. Because you are not iterating anything, you don't even need the loop. Replace the entire while loop with the code below. Please upvote and accept answer if it solves/helps you with your problem.
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[0] + "?");
answers[0] = scanner.nextInt();
System.out.println("Do you prefer " + options[1] + "?");
answers[1] = scanner.nextInt();
System.out.println("Do you prefer " + options[2] + "?");
answers[2] = scanner.nextInt();
System.out.println("Do you prefer " + options[3] + "?");
answers[3] = scanner.nextInt();
System.out.println("Do you prefer " + options[4] + "?");
answers[4] = scanner.nextInt();
Also, please note this:
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
won't work. Instead of result[i] = [answers[i]];, do result[i] = Integer.parseInt(answers.get(i)).
This is part causing the unexpected behaviour: result[i] = [answers[i]];
From what I understood, you want to implement this:
For each option, store the user choice like 0 or 1, 0 for left, 1 for right
For each user choice, store the string value of the choice, i.e., for the 1st question if the user inputs 0, mild should be captured
Calculate scores by comparing string value of user input against a branching construct, switch case here
The problem is in step 2, the current code result[i] = [answers[i]]; does not express this operation properly.
answers[i] stores the user choice 0 or 1, step 1 operation. So to convert it to the corresponding choice in string step 2 operation, something like this should be done
(options[i].split(" or "))[answers[i]]
Explanation:
Pick up the complete string for each answer
Divide the string into two parts(array with 2 indexes 0 and 1), left and right, using a delimiter, " or " in this case
pick up the left or right based on the value stored in answers[i](the user input)
This should let the code behave as expected :)
There are other aspects that can be improved in the code though, as others have already suggested.

How to check for Duplicate strings on an array

I'm kind of new to java and I'm trying to make a guessing game that looks for User01's duplicate. I'm encountering a problem and I have no idea how do I fix this. My goal is to check if User01 has already entered that specific word. Here is my code as of right now:
public static void main(String[] args) throws InterruptedException{
int k = x;
boolean Given = false;
boolean Given2 = false;
//Playerone and x are in Global Declarations.
for(int j = 0; j < x; j++, k--){
if(j == 0){
System.out.print("Please enter " + k + " words that Player 2 will Guess:");
Playerone[j] = input.nextLine();
System.out.println(j);
}
else if(j == x-1){
System.out.print("Last one:");
Playerone[j] = input.nextLine();
System.out.println(j);
}
else {
System.out.print(k + " more words:");
Playerone[j] = input.nextLine();
System.out.println(j);
}
do {
int Duplicates = 0;
while(Duplicates > j && Playerone[Duplicates] == Playerone[j]){
Duplicates++;
}
Given2= Duplicates < j;
if(Given2 == false){
Given2 = true;
System.out.println("It's already given");
Playerone[j] = input.nextLine();
}
}while(Given2 = true);
}
I tried placing do below the start of for-loop, and it doesn't fixed the problem I'm having.
There is a problem with the condition:
Duplicates>j
which is always false and doesn’t allow Duplicates++
also Duplicates=0; Happens every time User1 gives a word so this will never work to count Duplicates anyway.
Fist of all move Duplicates=0; before the fist for loop
So what I would instead of the last do...while is :
Given=false;
for(int c=0;c<=j;c++){
while(Playerone[j]==Playerone[c])
//duplicate found
System.out.println(“Already exists”);
Playerone[j]=input.nextLine();
Given=true;
}
//these loop also prevent user to give again a word that already exists
}
if(Given) Duplicates++;

Stuck in logic for movie guess game in java (by udacity)

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

Loop in a loop and If statement?

I am a beginner programming, I want to ask multiple questions using arrays and tell the user whether he got each question right or wrong, which I managed to get it running, but now how do I implement the code so that the user will only have up to 3 attempts to get a question right.
for(int n = 0; n <QArray.length; n++)
{
System.out.println("Question" + (n+1));
System.out.println(QArray[n]);
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n]))
{
System.out.println("That is correct!");
}
else
{
System.out.println("That is incorrect!");
}
}
So if I correctly understand your goal, you've a list of questions, and whilst they have made fewer than three failed attempts at them, you would like for the users to get to try and answer them?
Using your existing style, you could do something like
for(int n = 0; n < QArray.length; n++)
{
System.out.println("Question" + (n+1));
System.out.println(QArray[n]);
int incorrectAnswers = 0;
while(incorrectAnswers < 3)
{
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n]))
{
System.out.println("That is correct!");
break;
}
else
{
System.out.println("That is incorrect!");
incorrectAnswers++;
}
}
}
Depending how the data is displayed and transferred and concerns regarding security etc, it would make for easier to manage code to have a QuestionAnswer object that contains the question and the answer, as well as a method for what constitutes a valid answer (e.g. case insensitive, or maybe you want to accept multiple words etc, whatever works for your case), so you could end up with code that looks like the below.
for(int i = 0; i < questionAnswerArray.length; i++)
{
QuestionAnswer qa = questionAnswerArray[i];
System.out.println("Question " + (i+1));
System.out.println(qa.getQuestion());
int incorrectAnswers = 0;
while(incorrectAnswers < 3)
{
String ans = scanner.nextLine();
if (qa.isValidAnswer(ans))
{
System.out.println("That is correct!");
break;
}
else
{
System.out.println("That is incorrect!");
incorrectAnswers++;
}
}
}
Try to use while with the number of attempt you need:
for (int n = 0; n < QArray.length; n++) {
System.out.println("Question" + (n + 1));
System.out.println(QArray[n]);
int attempt = 3;
while (attempt > 0) {
System.out.print("Please enter the answer: ");
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n])) {
System.out.println("That is correct!");
break;
} else {
System.out.println("That is incorrect!");
}
attempt--;
}
}
Put a second loop inside the first.
for(int n = 0; n < QArray.length; n++) {
boolean correct = false;
for(int m = 0; m < 3; m ++) {
String ans = scanner.nextLine();
if (ans.equalsIgnoreCase(AArray[n])) {
System.out.println("That is correct!");
correct = true;
break;
} else {
System.out.println("That is incorrect!");
}
}
if(!correct) {
//something
} else {
//something else
}
}
Note the break;. That command will exit the inner for-loop (which contains the scanner input) when a correct answer is submitted. If the user doesn't get the right answer in 3 tries, the for-loop will end by reaching the end of its counter.

Simple game of hangman with two character arrays. They get six tries. First user enters a word the second user guesses the word through _ blanks

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.

Categories