1

I'm learning java and I have a problem:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.util.*;


public class edytor{
  public static void main(String[] args) throws FileNotFoundException
    {
    Scanner czynowy = new Scanner(System.in);

    System.out.println("Do you wanna editing existing file?");
    String tn = czynowy.nextLine() ;
    if(tn=="t")
{System.out.println("bleble"); }
    Scanner odpowiedz = new Scanner(System.in);

    System.out.println("Type file name");
    String polozenie = odpowiedz.nextLine() ;
        System.out.println("################################");
      PrintWriter zapis = new PrintWriter(polozenie);
    Scanner tekst = new Scanner(System.in);
    String tekst1 = tekst.nextLine() ;
      zapis.println(tekst1);
      zapis.close();

  }
}

It's compiling, but when in string tn I type t char this doesn't print "bleble". What should I do to make it work? Greetings!

littlewolf
  • 173
  • 1
  • 2
  • 19
Zielpak
  • 98
  • 9

2 Answers2

3
if (tn.equals("t") {...}

String is an object, and if you create 2 strings, even if they will have same value, they won't be equal to eachother

string1 == string2 // false

the == checks the object identity. while the .equals() method in String, checks the value.

The other way of doing this will be to use for loop, to loop through every char in each string, and check if it matches the character with the same place in another string.

or in your case, do this:

if (tn.getBytes()[0] == 't') {...}
Victor2748
  • 4,149
  • 13
  • 52
  • 89
3

You need to use

if (tn.equalsIgnoreCase("t") {
   ...
}

The reason you cannot compare two Strings with == is because Strings are objects. When you try to compare two objects directly, you are comparing their locations in memory. So, even if the contents of two Strings may be equal, their memory locations will not be equal.

Tetramputechture
  • 2,911
  • 2
  • 33
  • 48