-2

I've been trying to create a program that censors a word but I was having difficulty with that so I tried going back to some of the fundamental code and testing it and I am coming across an odd result.

import java.util.Scanner;

public class TextCensor
{
public static void main(String[] args)
{
        String input;
        Scanner keyboard = new Scanner(System.in);
        input = keyboard.nextLine();
        int length = input.length() - 1;

        if (length + 1 >= 3)
        {

            for (int i=0; i<(length - 1); i=i+1 )
            {
                char first = input.charAt(i);
                char second = input.charAt(i+1);
                char third = input.charAt(i+2);

                String censorCheck = "" + first + second + third;

                if (censorCheck == "tag")
                {
                    System.out.println("success");
                }
                else
                {
                    System.out.println(censorCheck);
                }
            }
        }
        else
        {
            System.out.println(input);
        }
}
}

If I input the string "adtag" I will obtain the following output:

adt
dta
tag

yet "success" will never be printed despite the fact that I have printed a censorCheck that is equal to "tag".

Craig
  • 395
  • 3
  • 14

3 Answers3

0

You are trying to check whether both instance of String is same or not instead of checking contents of both string. You should try censorCheck.equals("tag") .

sauumum
  • 1,638
  • 1
  • 19
  • 36
0

To compare whether contents of two string are equal or not in JAVA you should use the equals() method. You cannot compare the value of two string by the == operator . In your case use if (censorCheck.equals("tag")) and see if you get the desired result.

Arka Prava Basu
  • 2,366
  • 3
  • 18
  • 34
0

String is an object. You have to compare objects by equals():

censorCheck.equalsIgnoreCase("tag")

Ignore case works fir upper letters as well.

Only for primitives you can use comparison by ==:

3 == 3

yarco
  • 172
  • 7