Как заменить строку целевого массива и изменить ее на строку ввода пользователя - PullRequest
2 голосов
/ 28 апреля 2020

так что в принципе я новый в stackoverflow. У меня есть этот код, который заменяет каждое подчеркивание в пользовательскую строку.

public class MainActivity extends AppCompatActivity {
private String result="";
private String textresult = "The red fox jumps over the lazy dog";
EditText text;
Button btn;
public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = findViewById(R.id.editText);
        btn = findViewById(R.id.button_edittext);
        final TextView tvtext = findViewById(R.id.result);
        final String les = textresult.replaceAll("[a-z]", "_");
        tvtext.setText(les);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v

    String les1 = textresult.replaceAll("[a-z]", "_");
    final String sampleText = text.getText().toString().trim();
    int noOfBtns = sampleText.length();
    int noOftext = les1.length();


    final TextView[] btns = new TextView[noOfBtns];

    for(int i=0;i<noOfBtns;i++)
    {
        btns[i] =   new TextView(MainActivity.this);
        btns[i].setText(sampleText.substring(i,i+1));

        result = result+btns[i].getText().toString();
        char[] c = result.toCharArray();

          les1 = changeCharInPosition(i, c[i], les1);*/
                tvtext.setText(les1);
        }
    }
});
}

, поэтому выходные данные будут такими:

**T__ ___ ___ ____ ____ ___ ____ ___.**

проблема: так как я могу настроить таргетинг на первую длину текста до конца текста и обновить или заменить каждая длина символа, например:

, когда пользователь вводит слово и обновляет или заменяет:

**user input: the red
display: the red ___ ____ ____ ___ ____ ___.**

и если пользователь вводит неправильную букву для слова, оно будет отображаться *:

**user input: the red fix
display: the red f*x ____ ____ ___ ____ ___.**

крайне нужна помощь для этого кода. спасибо !!

Ответы [ 2 ]

1 голос
/ 28 апреля 2020

Ваш пример кода не JavaScript, но вы пометили свой вопрос как таковой.

Поэтому я даю простой JS ответ:)

const text = "The red fox jumps over the lazy dog."

const question = document.getElementById('question')
const guess = document.getElementById('guess')

// handling input
const check = (g, t) => {
  const gArr = [...g]
  const tArr = [...t]

  const r = []

  tArr.forEach((e, i) => {
    // if the character in the text is ' ' or '.'
    // just return it as it is
    if (e === ' ' || e === '.') {
      r.push(e)
    } else if (!gArr[i]) {
      // if the quess is shorter than the real text, then
      // return _ in not yet quessed places
      r.push('_')
    } else if (gArr[i]) {
      if (gArr[i] === e) {
        // if the guess is correct,
        // then return the correct guess
        r.push(e)
      } else {
        // if the guess is incorrect,
        // then return '*'
        r.push('*')
      }
    }
  })
  return r.join('')
}

// set the stage
question.innerHTML = check(guess.value, text)

// react to input events
guess.addEventListener('input', function(e) {
  const r = check(e.target.value, text)
  question.innerHTML = r
})
<label for="guess">Guess the text: <input id="guess" type="text"/></label>
<div id="question"></div>
1 голос
/ 28 апреля 2020

Я думаю, что вы пытаетесь обновить все эти TextViews на основе текущего пользовательского ввода из EditText. Добавьте TextWatcher к вашей переменной text:

text.addTextChangedListener(new TextWatcher(){...

. Вы сами должны выяснить, какой метод интерфейса TextWatcher вам понадобится. Удачи!

...