2

スキャナが文字列値「end」を受け取ったときに終了するループを書いています。ただし、「終了」値でテストすると、ループが続行されます。論理的には、file = 入力の場合、end と入力したにもかかわらず、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);
4

2 に答える 2

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

そして、ええ、それはひどいです。

于 2010-01-28T23:08:48.060 に答える
2

あなたの問題はここにあると思います:

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

"end" を 2 回入力しないとfile、次のチェックの前に上書きされます。

また、私はあなたが欲しいと思います

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

編集:コメントに応じて、から== "end"に変更するだけ.equals("end")で済みます。

于 2010-01-28T23:11:39.777 に答える