新扫描仪出错

时间:2015-03-27 10:14:51

标签: java string java.util.scanner

我的程序中有一个问题,我希望我的程序用户编写他想要使用的文件,然后使用循环,根据他输入的单词,将使用一个文件。 Butmy programm从不进入一个循环,我不知道问题的来源。

这是我的代码:

        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

3 个答案:

答案 0 :(得分:4)

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

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

请参阅 - How do I compare strings in Java?

答案 1 :(得分: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 
 } 

答案 2 :(得分:0)

试试这个:

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