1

I am trying to create a method that will consume two Strings. It will Compare String 1 with String 2 and will replace all unfound chars with '_'. For example if String 1 = "Hello"; String 2 = "eo" then the method will return String 1 as "_e__o" Here is my code:

static String getRevealedChars (String s1, String s2)
{
    for (int i = 0; i < s1.length(); i++)
    {
        for (int c = 0; c < s2.length(); c++)
        {
            if (s1.charAt(i) == s2.charAt(c))
            {
                break;
            }
            else 
            {
                // this is where I get my Error
                s1.charAt(i) = '_';
            }
        }
    }
}

However, when I run this code I get a "unexpected type" error at s1.charAt(i) = '_';. I'm really new to java, thanks in advance.

gurnii
  • 39
  • 1
  • 7

1 Answers1

0

Replace datatype of s1 and s2 from String to StringBuilder, then use setCharAt() instead of charAt() as follows:

StringBuilder s1 = new StringBuilder("hello");
StringBuilder s2 = new StringBuilder("eo");

static String getRevealedChars (StringBuilder s1, StringBuilder s2)
{
    for (int i = 0; i < s1.length(); i++)
    {
        for (int c = 0; c < s2.length(); c++)
        {
            if (s1.charAt(i) == s2.charAt(c))
            {
                break;
            }
            else 
            {
                // this is where I corrected Error
                s1.setCharAt(i, '_');
            }
        }
    }
}

Hope this helps. Good luck.

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
user3701435
  • 107
  • 8