-4

I am having trouble with the if statement even when the file explicit.txt only has the word abazure the program does not enter the if statement. The program just passes the if statement and outputs the word abazure again.

import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class Manzai {

    public static void main(String[] args) {
    String word;
    Scanner input = null;
    PrintWriter output = null;

    try
    {
        input = new Scanner(new File("explicit.txt"));
        output = new PrintWriter(new File("censored.txt"));
    }
    catch(FileNotFoundException e)  
    {

        System.out.println("File explicit.txt was not found");
        System.exit(0);
    }

    while(input.hasNext())
    {
        word = input.next();

        if(word=="abazure")
        {
            word = "a******";
        }

        output.print(word + " ");
    }
    input.close();
    output.close();
}
}
blueguisee
  • 11
  • 3

3 Answers3

5

== in case of objects in general just checks if two reference variables refer to the same object. use equals() method to checkfor string equality

    if(word=="abazure")

should be

    if("abazure".equals(word))
PermGenError
  • 45,977
  • 8
  • 87
  • 106
1

try

if(word.equals("abazure")){
   // do something
}

String#equals()

Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
1

The operator, ==, tests to see if two object reference variables refer to the exact same instance of an object.

The method, .equals(), tests to see if the two objects being compared to each other are equivalent -- but they need not be the exact same instance of the same object.

So you should be using something like follows for youe check of equality:

 if("abazure".equals(word))
Amar
  • 11,930
  • 5
  • 50
  • 73