[英]Writing Output to a text file
因此,我試圖創建一個程序,以名字和姓氏的形式輸入內容,然后將其打印到Output.txt文件中。 我對編程有點陌生,我想以此為恥。
我只是在程序的最后部分不斷出現錯誤。
PrintInitials.java:21: error: <identifier> expected
} output.close();
^
1 error
這是我的代碼
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.*;
public class PrintInitials
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String first; // first name
String last; // last name
System.out.print("Enter your first and last name separated by a space: ");
first = stdIn.next();
last = stdIn.next();
File file = new File("Output.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
} output.close();
}
像這樣做:
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter your first and last name separated by a space: ");
String first = stdIn.next(); // first name
String last = stdIn.next(); // last name
stdIn.close();
try (FileWriter writer = new FileWriter(new File("Output.txt"), true); // autocloseable
PrintWriter output = new PrintWriter(writer)) { // autocloseable
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
} catch (IOException e) {
e.printStackTrace();
}
作家將自動關閉。
問題在於,在關閉流之前,您要關閉方法主體。 因此,“ output.close();” 在方法之外並進入類主體。
您的新代碼應如下所示:
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.*;
public class PrintInitials{
public static void main(String[] args){
try{
Scanner stdIn = new Scanner(System.in);
String first; // first name
String last; // last name
System.out.print("Enter your first and last name separated by a space: ");
first = stdIn.next();
last = stdIn.next();
File file = new File("Output.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
output.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
如果您還沒有,請查看Java Basic語法和PrintWriter的文檔,以檢查哪種方法引發了哪些異常,以便您可以像我上面所做的那樣捕獲它們並對其進行處理,或者直接將它們傳遞出去。
同樣,使用諸如eclipse之類的IDE可以在編碼時實時顯示所有語法錯誤,因此您不必每次都自己編譯以檢查語法是否正確。 同樣,大多數IDE經常附帶針對特定錯誤的解決方案。 除此之外,它還會警告您有關哪種方法拋出什么異常,以便您可以捕獲它們。
嘗試這個
BufferedWriter br= new BufferedWriter(new FileWriter(file)){
br.write(first + " " + last);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.