0

I have a problem in my programm, I want the user of my programm to write the file he wants to use and then with loops, depending on the word he typed, a file will be used. Butmy programm never enters in one loop and I don't know where the problem comes from.

Here is my code:

        System.out.println("Nom du test case à lancer ? : ");
    Scanner saisieUtilisateur = new Scanner(System.in); 
    //on rentre l'adresse du fichier texte :
    String str = saisieUtilisateur.next();
    System.out.println(str);
    //Integer val = saisieUtilisateur.nextInt();
    //System.out.println(val);
    String chaine = "";
    String File="";
    int i=1;

    //Choix du fichier a prendre en compte suivant le choix de l'utilisateur
    if (str == "hello"){
        File = "C:\\exempleANT\\helloWordTexte.txt";
        System.out.println("dans la boucle 1");
    }
    else if(str == "bye"){
        System.out.println("dans la boucle 2");
        File =  "C:\\exempleANT\\FichiersTestExempleHelloWord\\bye.txt";
    }
    else if(str == "fake"){
        System.out.println("dans la boucle 3");
        File =  "C:\\exempleANT\\FichiersTestExempleHelloWord\\helloWordTexteFake.txt";
    }
    else  {
        System.out.println("ErreurTexte!");
        System.out.println("dans la boucle 4");

    }

And here is the result in the console when I run the programm and I type hello.

hello
hello
ErreurTexte!
dans la boucle 4
Anatch
  • 443
  • 1
  • 5
  • 20

3 Answers3

4

Use .equals for string equality rather than '=='.

 if (str.equals("hello")){
     ...
 }

See - How do I compare strings in Java?

Community
  • 1
  • 1
Kevvvvyp
  • 1,704
  • 2
  • 18
  • 38
1

If you are using JAVA 7 than it will be done simple way

//str is your String to get match with
    switch (str) {
    case "hello":
        File = "C:\\exempleANT\\helloWordTexte.txt";
        System.out.println("dans la boucle 1");
        break;
    case "bye":
        System.out.println("dans la boucle 2");
    File = "C:\\exempleANT\\FichiersTestExempleHelloWord\\bye.txt";
        break;
    case "fake":
        System.out.println("dans la boucle 3");
        File="C:\\exempleANT\\FichiersTestExempleHelloWord\\helloWordTexteFake.txt";
        break;
    default:
        System.out.println("ErreurTexte!");
    System.out.println("dans la boucle 4");
    }

or you can use

 if (str.equals("hello")){
 ...// old way 
 } 
Bhargav Modi
  • 2,605
  • 3
  • 29
  • 49
  • @Anatch ur welcome buddy if considered as solution than accept it buddy I suggest to use Switch case instead of If/else as its more efficient if ur using java 7 – Bhargav Modi Mar 27 '15 at 10:29
  • I am not using JAVA 7 so it is only the old way that works, sorry – Anatch Mar 27 '15 at 10:33
0

Try this:

 if (str.equals("hello"))
    {
        File = "C:\\exempleANT\\helloWordTexte.txt";
        System.out.println("dans la boucle 1");
    }
i23
  • 508
  • 2
  • 12