Java Scanner输入不等于自身?

时间:2010-01-28 23:05:12

标签: java java.util.scanner

我正在编写一个循环,当Scanner收到字符串值“end”时它将退出。但是,当使用“结束”值进行测试时,循环继续。逻辑上如果file =输入,那么if(file ==“end”)为false,即使我输入了!我的代码中是否有明显的错误?

String file = "";
    Scanner in = new Scanner(System.in);
    ArrayList<Integer> fileInput = new ArrayList<Integer>(); 

    while(file!="end") {
        // Scan for filename/end program
        System.out.println("Provide the name of a file in the \"bin/\" folder, i will assume it's .txt");
        file = in.nextLine();

        System.out.println("." + file + ".");
        if(file!="end") {
            file= "bin/" + file + ".txt";

            // start reading
            try {
                // If file found then carry on
                BufferedReader openFile = new BufferedReader(new FileReader(file));
                fileInput = readIn(openFile);
                int lowerBound = getLower(fileInput);
                int upperBound = getUpper(fileInput);

                System.out.println("Lower Bound: " + lowerBound);
                System.out.println("Upper Bound: " + upperBound);

                // file not found
            } catch (FileNotFoundException e) {
                System.out.println("File not found!");
            }
        }
    }
    System.out.println("Goodbye!");
    System.exit(0);

2 个答案:

答案 0 :(得分:5)

在Java中,您必须使用.equals()来实现字符串相等;否则它会进行参考比较。

String s1 = "end";
String s2 = "end";  // different string in memory
s1 == s2            // false: not the same string
s1.equals(s2)       // true: have the same characters
"end".equals(s1)    // also true
"end" == s1         // false

是的,它很糟糕。

答案 1 :(得分:2)

我认为你的问题在这里:

if(file!=file2) {
    file= "bin/" + file + ".txt";

除非您输入两次“结束”,否则在下次检查前会覆盖file

另外,我认为你想要

if(!file.equals(file2)) {
    file= "bin/" + file + ".txt";

修改:为了回复您的评论,只需从== "end"更改为.equals("end")即可。