1

I'm currently creating a mobile application containing flag guessing games using Android Studio 3.2. For one of the games I have to display a random flag and the corresponding name (covered with dashes). The user can input a letter into the edit text box underneath and click the submit button. If the user gets the answer right then dashes with that letter are removed to show the actual letter.

Image showing UI of app

The problems for me start with replacing each dash individually. When I enter a letter and submit it, all the dashes turn into that same letter.

package com.example.anisa.assignment1;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Random;

public class GuessHints extends AppCompatActivity
{
    private ImageView flag;
    private int randIndex;
    public char[] answers = {};

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guess_hints);
        displayHintsFlag();
        splitCountryNameLetters();
    }

    public void displayHintsFlag()
    {
        flag = findViewById(R.id.displayHintsFlag);
        Random r = new Random();
        int min = 0;
        int max = 255;
        randIndex = r.nextInt(max-min) + min;
        Country countries = new Country();
        int randomHintsFlagImage = countries.countryImages[randIndex];
        flag.setImageResource(randomHintsFlagImage);
    }

    public void splitCountryNameLetters()
    {
        Country countries = new Country();
        String randomHintsFlagName = countries.countryNames[randIndex];
        TextView hintsQuestion = (TextView) findViewById(R.id.countryDashesDisplay);
        String hintsQuestionString;
        int flagNameLength = randomHintsFlagName.length();
        char letter;

        for (int i = 0; i < flagNameLength; i++)
        {
            Log.d("Flag: ",randomHintsFlagName + "");
            hintsQuestionString = hintsQuestion.getText().toString();
            letter = '-';
            hintsQuestion.setText(hintsQuestionString + " " + letter);
        }
        Log.d("Answers: ", answers + "");
    }

    public void checkUserEntries(View view)
    {
        Country countries = new Country();
        String randomHintsFlagName = countries.countryNames[randIndex];
        int flagNameLength = randomHintsFlagName.length();
        TextView hintsQuestion = (TextView) findViewById(R.id.countryDashesDisplay);
        String hintsQuestionString = hintsQuestion.getText().toString();
        EditText userEntry = (EditText) findViewById(R.id.enterLetters);
        String userEntryText = userEntry.getText().toString();

        //int numCorr = 0;
        char letterChar = userEntryText.charAt(0);

        for(int k = 0; k < flagNameLength; k++)
        {
            if((letterChar == randomHintsFlagName.charAt(k)))
            {
                //numCorr++;
                hintsQuestionString = hintsQuestionString.replace(hintsQuestionString.charAt(k), letterChar);
            }
        }
        hintsQuestion.setText(hintsQuestionString);
    }

    public void nextGuessHints(View view)
    {
        Button submitButtonHints = (Button) findViewById(R.id.submitLetterButton);
        submitButtonHints.setText("Next");
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
        startActivity(new Intent(GuessHints.this, MainActivity.class));
        finish();
    }
}

I know the issue is with the use of k index, but not sure how to solve this problem as it is in a for loop.

2
  • Were our answers helpful? Commented Mar 11, 2019 at 22:29
  • Yes they were very helpful thank you Commented Mar 22, 2019 at 19:23

2 Answers 2

1

Say you have a starting String such as Italia.
The user enter the letter i, and what should happen is

------ > I---i-

Let's start by transforming the to-be-guessed String to a dashed out version

final String toBeGuessed = "Italia";                     // Italia
final String dashed = toBeGuessed.replaceAll(".", "-");  // ------

Now the user enter i as a guessed letter. We transform it to lowercase for later comparison.

final char letter = Character.toLowerCase('i');

What we need to do is update the dashed String, and for that we'll use a StringBuilder.
Using a StringBuilder allows us to set single characters.

// Create the StringBuilder starting from ------
final StringBuilder sb = new StringBuilder(dashes);

// Loop the String "Italia"
for (int i = 0; i < toBeGuessed.length(); i++) {
    final char toBeGuessedChar = toBeGuessed.charAt(i);

    // Is the character at the index "i" what we are looking for?
    // Remember to transform the character to the same form as the
    // guessed letter, maybe lowercase
    final char c = Character.toLowerCase(toBeGuessedChar);

    if (c == letter) {
        // Yes! Update the StringBuilder
        sb.setCharAt(i, toBeGuessedChar);
    }
}

// Get the final result
final String result = sb.toString();

result will be I---i-.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the code- this was very helpful and I managed to complete my app in the end!
@Anisa hey! I'm glad you did it in the end ;) If you want you can mark the answer as accepted!
Sure will do :)
0

As in Java String is immutable so you can't replace any string with another String.

 hintsQuestionString = hintsQuestionString.replace(hintsQuestionString.charAt(k), letterChar);

the above line won't work in Java.

Either You can user StringBuilder Class to replace the string

Or

You don't have to spit the string because it won't work in Java as String class in Java is immutable.

You can simply set the text in TextView

this string you have got from the user String hintsQuestionString = hintsQuestion.getText().toString();

then compare the whole string using the equals method and if the entered string will match then you have to set the text. I have taken the countryName variable by own, you have to replace this string with your taken variable.

if(countryName.equals(hintsQuestionString))
  {
    hintsQuestion.setText(hintsQuestionString);
  }

I hope, this will help you.

1 Comment

Thanks, however the problem was that I had to replace this string multiple times so it caused issues

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.