[英]how can i make a write function that not in the main
我有一個代碼:
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class Tutorial6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choose;
System.out.println("Enter your choice: ");
choose = scanner.nextInt();
if(choose == '1'){
write();
}
else{
read();
}
}
public static void write() throws IOException, ClassNotFoundException{
PrintWriter output = new PrintWriter(new FileWriter("users.txt", true));
Scanner scanner = new Scanner(System.in);
String name, address, ages;
System.out.println("Enter your name: ");
name = scanner.nextLine();
System.out.println("Enter your address: ");
address = scanner.nextLine();
System.out.println("Enter your ages: ");
ages = scanner.nextLine();
output.println(name + " " + address + " " + ages + "\n");
output.flush();
output.close();
}
public static void read(){
Scanner input = new Scanner (new File("users.txt"));
while (input.hasNext()) {
System.out.println(input.nextLine());
}
input.close();
}
}
它有一個稱為未處理異常類型的錯誤。 我該如何解決它,我嘗試將寫入和讀取 function 放在不同的 java class 中並且工作正常。 但我希望它像注冊文本界面應用程序一樣工作。
環繞write
function 調用與try-catch
塊
if(choose == '1'){
try{
write();
} catch(Exception e){
// handle exception here
}
} else {
read();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.