import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class CreateTextFile
{
private Formatter formatter;
public void openFile()
{
try
{
formatter = new Formatter("clients.txt");
}
catch (SecurityException securityException)
{
System.err.println("You do not have permission to access this file");
System.exit(1);
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening or creating the file");
System.exit(1);
}
}
public void addRecords()
{
AccountRecord accountRecord = new AccountRecord();
Scanner scanner = new Scanner(System.in);
System.out.printf("%s%n%s%n%s%n%s%n", "To terminate input, type the end-of-file indicator", "when you are prompted to enter input", "On Unix/Linux/Mac OS X type <control> d then press Enter", "On Windows type <ctrl> z then press Enter");
while (scanner.hasNext())
{
try
{
accountRecord.setAccountNumber(scanner.nextInt());
accountRecord.setFirstName(scanner.next());
accountRecord.setLastName(scanner.next());
accountRecord.setBalance(scanner.nextDouble());
if (accountRecord.getAccountNumber() > 0)
formatter.format("%d %s %s %,.2f%n", accountRecord.getAccountNumber(), accountRecord.getFirstName(), accountRecord.getLastName(), accountRecord.getBalance());
else
System.out.println("Account number must be greater than 0");
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file");
return;
}
catch (NoSuchElementException noSuchElementException)
{
System.err.println("Invalid input. Try again");
scanner.nextLine();
}
System.out.printf("%s %s%n%s", "Enter account number (>0),", "first name, last name and balance.", "?");
}
scanner.close();
}
public void closeFile()
{
if (formatter != null)
formatter.close();
}
}
我只是想知道为什么在openFile()
中的catch
块被终止时会使用System.exit()
,而在addRecords()
中的catch
块终止时会使用return
。是否有建议在何时使用每个的方式?