我试着做些这样的工作:
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时,文件会被保存,但是下面的语句不会执行,它会突然终止。
如果我输入了*在输入最后一行后,它应该能够执行out.println(filename+" is saved and closed")
当前产出:
D:\JavaEx\FILE-IO>java PrintWrit1
Enter the filename : sample
Enter the file content, enter * after finishing
line1
line2
*预期产出:
D:\JavaEx\FILE-IO>java PrintWrit1
Enter the filename : sample
Enter the file content, enter * after finishing
line1
line2
*
sample is saved and closed发布于 2019-02-09 09:22:04
您正在比较字符串* wrongly.You应该使用equals()方法。请更换
while((text=input.nextLine()) != "*")至
while(!(text=input.nextLine()).equals("*"))https://stackoverflow.com/questions/54604857
复制相似问题