0

I have trouble with my code. I need to replace element in Array if condition is true. Inputs are:

dashedCapital = "------";
input = "a";
capital = "Warsaw";

Code should check if capital contains input and if yes replace "-" in dashedCapital to character from input at specified position:

  public static String changeDashedCapital(String dashedCapital, String input, String capital){
  String[] capitalArray = capital.split("");
  String[] dashedCapitalArray = dashedCapital.split("");
  String[] character = input.split("");

  for(int i = 0; i < capitalArray.length; i++){
    //System.out.println(i);
    //System.out.println(capitalArray[i] + character[0] + dashedCapitalArray[i]);
    if(capitalArray[i] == character[0]){
      dashedCapitalArray[i] = character[0];
    }
  }

  String result = Arrays.toString(dashedCapitalArray);
  System.out.println(result);
  return result;
}

Result is "------" but should be "-a--a-". What's going wrong?


John, thanks for your reply, it was helpful.

I edited my method so it's look like this now:

    public static String changeDashedCapital(String dashedCapital, String input, String capital){

  for(int i = 0; i < capital.length(); i++){
    if(capital.charAt(i).equals(input.charAt(0))) {
      String new_dashed = dashedCapital.substring(0,i)+input.charAt(0)+dashedCapital.substring(i);
      System.out.println(new_dashed);
    }
  }

  return "OK:";

Now i get this error:

    GetWord.java:69: error: char cannot be dereferenced
    if(capital.charAt(i).equals(input.charAt(0))) {
                        ^
    1 error

I don't understand why it's wrong. I using a equals() function. I also tried "==" operator but then nothing happens. What does it mean "char cannot be dereferenced"? How I could compare single chars from string with another chars from another string?

J W
  • 15
  • 1
  • 5
  • 2
    Instead of `.split("")` use `.toCharArray()` – Eran Mar 07 '18 at 14:01
  • for comparing strings use `equals()` the `==` operator compares objects just replace `capitalArray[i] == character[0]` to `capitalArray[i].equals(character[0])` – shahaf Mar 07 '18 at 14:06

1 Answers1

1

The reason it is not working is because your if for character equality is never true. You’re comparing strings of length 1 and not characters. You can quickly fix by changing if be using the string comparing function .equals()

if(capitalArray[i].equals(character[0])){
  ...
}

However, you should change your code and not just use this fix. Don’t split your stings into arrays, just use the .charAt() method to get a character at a particular index.

John
  • 101
  • 5