Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在while循环中使用字符串条件,java?_Java_String_While Loop - Fatal编程技术网

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

如何在while循环中使用字符串条件,java?,java,string,while-loop,Java,String,While Loop,该程序的目标是获取输入并创建日记条目,并在输入单词end时将输入输出到文件中。当我编译时,当我输入end时,程序不会终止,并且我的日记条目不会保存在输出文件中 在循环的每次迭代中,您都希望向用户分配更多输入任务。因为您想让用户至少输入一次,所以应该使用do while循环,例如 public class Diary { public static void main(String[] args) { Scanner input = new Scanner(Sys

该程序的目标是获取输入并创建日记条目,并在输入单词end时将输入输出到文件中。当我编译时,当我输入end时,程序不会终止,并且我的日记条目不会保存在输出文件中

在循环的每次迭代中,您都希望向用户分配更多输入任务。因为您想让用户至少输入一次,所以应该使用
do while
循环,例如

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.");
       }
 }

有几处需要修改。你应该做的是:

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

其目的是,当用户不输入“end”继续阅读时。

在代码中,如果
条目
有值
end
,循环将继续。但是,如果您想要相反的结果,请使用
操作员。此外,您没有在循环中使用新值重新分配
条目
,因此,如果条目的第一个值本身是
end
,它将导致无限循环

您需要将值重新分配给
条目

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

        entry= input.next();
    }

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

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

还要记住关闭输入:input.close();
String entry;
while(!"end".equals(entry = input.next())) {// I had used `!` logical operator
    output.print(entry + " ");
}