Steps to swap out an array string with a user-entered string

Greetings, I am a newcomer to StackOverflow and seeking assistance with a code snippet that replaces every underscore in a given string.

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

The desired output would be as follows:

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

The issue at hand involves targeting the first segment of text until the end and updating or replacing each character. For instance:

If a user inputs a word and updates it:

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

If the user input includes incorrect letters:

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

Your help with solving this problem is greatly appreciated. Thank you!

Answer №1

It appears that you are attempting to dynamically update multiple TextViews based on user input from an EditText field. To achieve this, you can attach a TextWatcher to your 'text' variable:

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

You will need to determine which method of the TextWatcher interface is necessary for your specific scenario. Best of luck with your implementation!

Answer №2

Even though your question was tagged as JavaScript, the example code you provided is not in JavaScript.

Here's a simple JS solution I came up with :)

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

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

// function to check the guessed text
const checkText = (guessedText, actualText) => {
  const guessedArray = [...guessedText]
  const actualArray = [...actualText]

  const result = []

  actualArray.forEach((char, index) => {
    if (char === ' ' || char === '.') {
      // handle spaces and periods
      result.push(char)
    } else if (!guessedArray[index]) {
      // handle cases where guess is shorter than actual text
      result.push('_')
    } else if (guessedArray[index] && guessedArray[index] === char) {
      // handle correct guesses
      result.push(char)
    } else {
      // handle incorrect guesses
      result.push('*')
    }
  })
  return result.join('')
}

// set initial display
question.innerHTML = checkText(guess.value, text)

// add event listener for input changes
guess.addEventListener('input', function(event) {
  const result = checkText(event.target.value, text)
  question.innerHTML = result
})
<label for="guess">Guess the text: <input id="guess" type="text"/></label>
<div id="question"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to send an object key/value pair to a Vue template?

I've made progress on my component, but I'm facing an issue where the links are going to http://localhost:5173/[object%20Object]. It seems like I've reached a mental roadblock. This is what my component looks like: <template lang="p ...

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

Obtain content from a div element using jQuery

Here is a snippet of HTML code that I am working with: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>Demo</title> </head> <body> <script src="jquery.js"></script> <scri ...

How does code execution vary when it is wrapped in different ways?

(function($) { // Implement your code here })(jQuery); jQuery(function($) { // Add your code here }); ...

Hidden Div on Google Maps no longer concealing

Since early December, the Google map on my site has been working perfectly. However, the other night, I noticed that the map now defaults to open when entering the site and cannot be closed. Strangely, all my Google maps are behaving this way even though n ...

Android causing multiple triggerings of pause and resume events in Ionic 3

Encountering a peculiar problem with the Ionic 3 pause and resume events. Every time I pause the application, the events trigger multiple times (2, 3 times, etc). Here is the snippet of code: this.platform.ready().then(() => { this.platform.pause.sub ...

What is the process of invoking a function in Typescript?

I am curious about how to effectively call this function in TypeScript. Can you guide me on the correct way to do it? type Fish = { swim: () => void }; type Bird = { fly: () => void }; function move(animal: Fish | Bird) { if ("swim" in ...

Utilizing a custom handler for Jquery Oembed functionality

I always preferred using my own function instead of using $(document).ready() to dynamically load an embed from a URL. This is what I have tried: function insertVideo(target,url) { $("#"+target).oembed(url); return false; } Here is an example of ...

Recursive functions that request input from the user

Currently in the process of developing a fun little script to help me organize and rate the movies in my personal collection. Among my list are a number of different movie titles that desperately need to be organized. The plan is to implement a merge-sort- ...

Having trouble extracting data from JSON object with an AJAX request

I have written some code to fetch JSON data from a servlet using an Ajax call. When the success function is executed, I am able to see the response in the console as Object: [{"userId":"dfeterter"}]. However, I am facing difficulty in accessing the value ...

Encountered an error while creating a PNG chart with node-export-server: Unexpected character '''

I am currently facing an issue when attempting to export a highchart graph using the node-export-server library; npm install highcharts-export-server -g Resource and Guide: https://github.com/highcharts/node-export-server#server-test Following the do ...

Error in finding the element with Selenium webdriver 2.0 was encountered

I can't seem to find the element with the specified class name. Here's a snippet of the HTML code: <a class="j-js-stream-options j-homenav-options jive-icon-med jive-icon-gear" title="Stream options" href="#"></a> I attempted to gen ...

Utilizing AJAX for fetching a partial view

My Web Forms legacy project had a feature where a panel would be displayed when the user clicked on a button. Now, I am working on rebuilding this functionality in C# MVC. The new view will utilize Javascript and AJAX to display a partial view as needed. ...

The Javascript navigate method has detected an incorrect language being used

Currently, I am facing a challenge while developing a React JS website related to the navigator issue. Even though my default browser is Chrome and English is set as the language preference, when I check navigator.language it displays "he-IL" instead of En ...

Unable to interpret encoded json information

I'm currently developing a basic chat system using PHP and jQuery with Ajax, but I've encountered an issue when trying to display a JSON encoded string through the ajax callback function. Below is the code for the ajax request: $.ajax({ url: ...

Utilizing JSON parsing on Android to dynamically place markers on a Google Map

I am trying to work with an API that gives me a URL, sends data in JSON format, and provides a response. My goal is to parse the JSON data and display locations on a Map in an Android app. While I don't expect anyone to write code for me, I would appr ...

Having trouble getting the onPress event to function properly on a custom button component in my React Native application

As a React Native beginner, I am currently working on a project where I am trying to create a custom button named "RoundedButton" using TouchableOpacity. However, when I attempt to trigger an event using onPress like , it does not seem to work for me. Here ...

Error message: "When using Webpack 4 with Bootstrap, a TypeError occurs where property 'jquery' is read as undefined."

I've recently delved into the world of webpack and everything seems to be running smoothly. However, when I run my webpack app, I encounter the following error within Bootstrap: var version = $.fn.jquery.split(' ')[0].split('.'); ...

Sorting elements in an array using jQuery is a common task that can be easily accomplished

Query: I am faced with a challenge in handling a table where rows are dynamically added upon button clicks. To allow users to rearrange the rows, I have incorporated the jquery-ui sortable() function for sorting purposes. Consider the following scenario: ...

Getting the ID from an onClick event and passing it to a function in React

I have a function set up with a template, and I want it to pass its ID when clicked. However, the current setup causes it to be clicked as soon as the element is loaded, preventing further clicks. import React from 'react' function PortItem(prop ...