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();
}
}
I was just wondering why in openFile()
the catch
blocks are terminated with System.exit()
and the catch
blocks in addRecords()
terminate with return
. Is there a recommended way of when each should be used?