如何在 while 循环 java 中使用条件字符串?

How do I use a string conditional in a while loop, java?

public class Diary {
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        PrintWriter output = null;
        try {
            output = new PrintWriter (new FileOutputStream("diaryLog"));
        } catch (FileNotFoundException e) {
             System.out.println("File not found");
             System.exit(0);
        }

        //Ok, I will ask the date for you here:
        System.out.println("Enter the date as three integers separated by spaces (i.e mm dd yyyy):");
        int month = input.nextInt();
        int day = input.nextInt();
        int year = input.nextInt();

        //And print it in the file
        output.println("Date: " + month +"/" + day + "/" + year);
        System.out.println("Begin your entry:");
        String entry= input.next();
        while("end".equals(entry))
        {
        output.print(entry + " ");
        }

        output.close();
        System.out.println("End of program.");
       }
 }

这个程序的目标是接受输入并创建日记条目,并在输入单词 end 时将输入输出到文件。当我编译程序时,当我输入 end 并且我的日记条目没有保存在输出文件中时,程序没有终止。

在循环的每次迭代中,您都希望让用户获得更多输入。因为你想要求用户至少输入一次,所以你应该使用 do-while 循环,例如...

String entry = null;
do {
    entry = input.nextLine();
} while (!"end".equals(entry));

有几处需要更改。你应该拥有的是:

 String entry= input.next();
    output.print(entry + " ");
    while(! "end".equals(entry))
    {

        entry= input.next();
    }

    output.close();
    System.out.println("End of program.");

本意是,趁用户不输入'end'继续阅读。

在您的代码中,如果 entry 的值为 end,则循环继续。但是,您想要相反的结果,因此请使用 ! 运算符。此外,您没有在循环内为 entry 重新分配一个新值,因此如果输入的第一个值本身就是 end,它将导致无限循环。

您需要重新为 entry 赋值:

String entry;
while(!"end".equals(entry = input.next())) {// I had used `!` logical operator
    output.print(entry + " ");
}

上面给出的解决方案是正确的,但不要忘记关闭您的 input。否则在 eclipse 中,当您尝试打开文本文件时,您将面临堆大小问题。