首页 > 解决方案 > 在for循环中对一个字符串使用字符串替换方法

问题描述

我目前正在使用 Android Studio 3.2 创建一个包含猜旗游戏的移动应用程序。对于其中一个游戏,我必须显示一个随机标志和相应的名称(用破折号覆盖)。用户可以在下方的编辑文本框中输入一个字母,然后单击提交按钮。如果用户得到正确的答案,则删除带有该字母的破折号以显示实际字母。

显示应用程序 UI 的图像

我的问题从单独更换每个破折号开始。当我输入一封信并提交时,所有的破折号都变成了同一个信。

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();
    }
}

我知道问题在于使用 k 索引,但不确定如何解决这个问题,因为它在 for 循环中。

标签: javaandroidfor-loop

解决方案


假设您有一个开始String,例如Italia.
用户输入字母i,应该发生的事情是

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

让我们首先将待猜测的版本String转换为虚线版本

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

现在用户输入i一个猜测的字母。我们将其转换为小写以供以后比较。

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

我们需要做的是更新虚线String,为此我们将使用StringBuilder.
使用 aStringBuilder允许我们设置单个字符。

// 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();

resultI---i-


推荐阅读