如何使用 PrintWriter 类实现输入" * "以保存文件并在接受扫描仪输入后退出的逻辑?



我正在尝试获得类似的工作方式:

import java.io.PrintWriter;
import java.io.IOException;
import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;

class PrintWrit1 
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(in);
        out.print("Enter the filename :t");
        String filename = input.nextLine();
        try(    PrintWriter pw = new PrintWriter(filename))
        {   
            out.println("Enter the file content, enter * after finishing");
            String text;
            while((text=input.nextLine()) != "*")
            {   pw.println(text);   }
            out.println(filename+" is saved and closed");
        }
        catch(IOException ioe)
        { ioe.printStackTrace();}
    }
}

创建文件,写入输出,但在按 ctrl-C 时不是 *,而是保存文件,但下面的语句不会执行并且会突然终止。

我正在寻找任何建议,如果我在输入最后一行后输入 *,它应该能够执行out.println(filename+" is saved and closed")

电流输出:

D:JavaExFILE-IO>java PrintWrit1
Enter the filename :    sample
Enter the file content, enter * after finishing
line1
line2
*

预期产出:

D:JavaExFILE-IO>java PrintWrit1
Enter the filename :    sample
Enter the file content, enter * after finishing
line1
line2
*
sample is saved and closed

您错误地比较了字符串 *。您应该使用equals()方法。请替换

while((text=input.nextLine()) != "*")

while(!(text=input.nextLine()).equals("*"))

最新更新