Issue
I want to export the character's name and gender to a text file. Also, I need to export on both Mac and PC computers. I've tried various methods, but none has worked for me or I might have placed them incorrectly.
I changed my code with my attempt:
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
public class Character {
public static void main (String[] args) {
String characterGender;
String characterName;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Ricardo's character creator!");
System.out.println("Is your character a boy or a girl?");
characterGender = scan.nextLine();
if (characterGender.equals("girl")) {
System.out.println("Awesome! Please enter her name: ");
characterName = scan.nextLine();
} else {
System.out.println("Awesome! Please enter his name: ");
characterName = scan.nextLine();
}
System.out.print("Alright! " + characterName + " has been created!");
PrintWriter out = new PrintWriter("Character.txt");
out.println(characterName);
out.println(characterGender);
out.close();
}
}
I'm getting an error like this:
Character.java:34: error: unreported exception FileNotFoundException; must be caught or declared to be thrown.
Solution
You need to handle the FileNotFoundException. This can be done either by:
Catching the exception (Preferred method):
PrintWriter out;
try {
out = new PrintWriter("Character.txt");
out.println(characterName);
out.println(characterGender);
out.close();
} catch (FileNotFoundException e) {
System.err.println("File doesn't exist");
e.printStackTrace();
}
or by throwing the exception:
public static void main (String[] args) throws FileNotFoundException
Note: import java.io.FileNotFoundException;
must be included in both cases.
Here is some java documentation on Exceptions.
Answered By - Grice
Answer Checked By - Pedro (JavaFixing Volunteer)