【问题标题】:Error in new Scanner [duplicate]新扫描仪出错[重复]
【发布时间】:2015-03-27 10:14:50
【问题描述】:

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

这是我的代码:

        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

【问题讨论】:

  • Butmy programm never enters in one loop 。 loop 在你的程序中在哪里?我确定您的意思是条件语句。
  • 提示考虑:您正在使用字符串的参考比较
  • 没有任何循环..但是尝试使用上面所说的 .equals() 方法。

标签: java string java.util.scanner


【解决方案1】:

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

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

见 - How do I compare strings in Java?

【讨论】:

  • 非常感谢@KevinPaton,现在可以使用了
  • 是的,但是我必须等待 8 分钟才能接受:)
【解决方案2】:

如果您使用的是 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 
 } 

【讨论】:

  • 非常感谢您提供的其他方式!
  • @Anatch 欢迎您的朋友,如果您认为是解决方案而不是接受它,朋友我建议使用 Switch case 而不是 If/else,因为如果您使用 java 7 会更有效
  • 我没有使用 JAVA 7,所以只能使用旧方式,抱歉
【解决方案3】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2015-10-02
    • 1970-01-01
    • 2015-09-06
    • 2012-10-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多