新扫描仪出错

Error in new Scanner

我的程序有问题,我希望我的程序的用户编写他想使用的文件,然后使用循环,根据他键入的单词,将使用一个文件。但是我的程序从来没有进入一个循环,我不知道问题出在哪里。

这是我的代码:

        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");

    }

这是我 运行 程序并键入 hello 时控制台中的结果。

hello
hello
ErreurTexte!
dans la boucle 4

使用 .equals 表示字符串相等而不是“==”。

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

参见 - How do I compare strings in Java?

试试这个:

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

如果您使用的是 JAVA 7,那么它将以简单的方式完成

//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");
    }

或者您可以使用

 if (str.equals("hello")){
 ...// old way 
 }