I have this code, that I'm trying to take the user input from the addEntry() method and write a method to save that to file.
public class GradeBook {
private String course;
private ArrayList<Person> students = new ArrayList<Person>();
private ArrayList<GradeBookEntry> entries = new ArrayList<GradeBookEntry>();
public GradeBook(String course){
this.course = course;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public void addStudent( Person student ){
students.add(student);
}
public void addEntry(){
System.out.println("Grade which student: ");
for (int i = 0; i < students.size(); i++) {
System.out.println(i + " " + students.get(i).getName());
}
Scanner reader = new Scanner(System.in);
int studentIndex = reader.nextInt();
reader.nextLine();
System.out.println("Enter the assessment name: ");
String assessmentName = reader.nextLine();
System.out.println("Homework (1) or exam (2): ");
int entryType = reader.nextInt();
reader.nextLine();
GradeBookEntry newEntry;
// TODO: create either a Homework or Exam entry
if( entryType == 1 ){
newEntry = new HomeworkEntry(assessmentName);
}
else {
newEntry = new ExamEntry(assessmentName);
}
// TODO: add getData method to the Homework and Exam
newEntry.getData();
newEntry.setStudent(students.get(studentIndex));
entries.add(newEntry);
}
This is the method below that I created but the text file doesnt have the correct data in it, I guess I somehow need the variables from the first method like "studentIndex" "entryType" etc., can you point me in the right direction?
public void writeFile(String fileName){
try {
FileWriter writer = new FileWriter(fileName);
for (int i=0; i<entries.size(); i++){
writer.write(students.get(i).toString());
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Overriding toString of Person class should be the correct way to go about this.
Related
I don't know what is wrong but it keeps me looping even though I pressed or entered 1 and I want it to call the subclass agent it doesn't but when I press 2 it calls the subclass what is wrong here I've been at it for 5-7hrs I think and my eyes be balling
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
class Person
{
protected String agentId = "20860132";
protected String password = "20020729" ;
protected String address;
public Person(String agentId,String password, String address)
{
this.agentId = agentId;
this.password = password;
this.address = address;
Scanner input = new Scanner(System.in);
System.out.println("[1]AGENT");
System.out.println("[2]CUSTOMER");
int choice = input.nextInt();
//here is where the code loops it just keeps repeating this lines
"System.out.println("[1]AGENT"); System.out.println("[2]CUSTOMER");"
if(choice == 1)
{
Agent agent = new Agent("Niel", "diko alam", "umay");
}
else if(choice == 2)
{
System.out.println("POTANGINA");
}
}
}
the block of code up here is suppose to call this class
class Agent extends Person
{
public Agent(String agentId, String password, String address)
{
super(agentId, password, address);
Scanner input2 = new Scanner(System.in);
System.out.println("[LOGIN]");
System.out.print("ENTER AGENT ID:");
int id = input2.nextInt();
System.out.print("ENTER PASSWORD:");
int pass = input2.nextInt();
if(id == 20860132 && pass == 20020729)
{
Scanner input = new Scanner(System.in);
System.out.println("[1]ADD CAR");
System.out.println("[2]SCHEDULE");
System.out.println("[3]RECORDS");
int choice2 = input.nextInt();
if(choice2 == 1)
{
boolean stopFlag = false;
do
{
List<String>cars = new ArrayList<String>();
System.out.println("[CARS]");
cars.add("Tayota");
cars.add("Hillux");
cars.add("Bugatti");
System.out.println(cars);
System.out.println("Enter Car:");
String car = input.nextLine();
cars.add(car);
System.out.println("Would you like to add more?");
System.out.println("[1]YES");
System.out.println("[2]NO");
String choice3 = input.nextLine();
addCar(cars);
if(!choice3.equals(1))
stopFlag = true;
}while(!stopFlag);
}
}
else
{
System.out.println("INCORRECT PLEASE TRY AGAIN.");
}
}
public void addCar(List<String> cars)
{
try
{
FileWriter fw = new FileWriter("cars.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(cars);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void schedule(String schedule)
{
try
{
FileWriter fw = new FileWriter("schedule.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(schedule);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void records(String record)
{
try
{
FileWriter fw = new FileWriter("records.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(record);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class Customer extends Person
{
private String customerId;
public Customer(String agentId, String password, String address, String customerId)
{
super(agentId, password, address);
this.customerId = customerId;
}
public void setCustomerId(String customerId)
{
this.customerId = customerId;
}
public String getCustomerId()
{
return customerId;
}
public void rentCar(String car)
{
try
{
FileWriter fw = new FileWriter("cars.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(car);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void viewSchedule(String schedule)
{
try
{
FileWriter fw = new FileWriter("schedule.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(schedule);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void extend(String record)
{
try
{
FileWriter fw = new FileWriter("records.txt", true);
PrintWriter pw = new PrintWriter(fw);
pw.println(record);
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Here is the main method
public class Finals
{
public static void main(String[] args)
{
Person person = new Person("20860132", "h208f32", "San luis");
Agent agent = new Agent("20860132", "h208f32", "San luis");
}
}
First line in the constructor of Agent calls super, which is the constructor of Person that will ask for input 1 and 2 again. That is your 'loop'. When you select 1, it will start creating another Agent object which will do the same thing again. If you keep selecting '1' you will never get past the super call in Agent.
Put the printing/input logic somewhere else, like in your main method. Constructors should be simple. For example, the logic in your Person constructor, move that to a static method in your Finals class (public static void createPerson) with the same arguments as what the constructor now has, and then call that from your main method instead of new Person. There is still much to improve beyond that, but that will probably fix your 'loop'.
i have a problem in my java exercise.
i need to print a multiply contact information to a file, but when i print more then 1 contact, only 1 contact is displayed in the file..
i tried to debug that but i cant find any mistake
i will put the code of my classes here:
This is Demo Class which i run the code from
public class Demo {
public static void main(String[] args) {
System.out.println("Insert number of Contacts:");
Scanner scanner = new Scanner(System.in);
int val = scanner.nextInt();
Contact[] contacts = new Contact[val];
for(int i = 0 ; i < val; i++) {
System.out.println("Contact #"+(i+1));
System.out.print("Owner: \n");
String owner = scanner.next();
System.out.print("Phone number: \n");
String phoneNum = scanner.next();
System.out.print("Please Select Group:\n"
+ "1 For FRIENDS,\n" +
"2 For FAMILY,\n" +
"3 For WORK,\n" +
"4 For OTHERS");
int enumNum = scanner.nextInt();
Group group;
switch(enumNum) {
case 1:
group=Group.FRIENDS;
break;
case 2:
group=Group.FAMILY;
break;
case 3:
group=Group.WORK;
break;
default:
group=Group.OTHERS;
}//switch end
contacts[i] = new Contact(owner,phoneNum,group);
}//loop end
System.out.println("Insert File name");
String fileName = scanner.next();
File f=null;
for(int i = 0 ; i < val; i++) {
if(i==0) {
f = new File(fileName);
contacts[0].Save(fileName);
}
else {
contacts[i].Save(f);
}
}
}
}
This is Contact Class:
enum Group {
FRIENDS,
FAMILY,
WORK,
OTHERS
};
public class Contact {
private String phoneNumber,owner;
private Group group;
PrintWriter pw = null;
public Contact(String owner ,String phoneNumber,Group group) {
setPhoneNumber(phoneNumber);
setOwner(owner);
setGroup(group);
}
public Contact(String fileName) {
File file = new File(fileName+".txt");
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public Contact(File file) {
try {
Scanner scanner = new Scanner(file);
phoneNumber=scanner.nextLine();
owner=scanner.nextLine();
String str=scanner.nextLine();
group = Group.valueOf(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
if(f.createNewFile()) {
System.out.println("File created");
pw = new PrintWriter(f); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
}
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
public void Save(File f) {
PrintWriter pw=null;
try {
pw = new PrintWriter(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.println(phoneNumber+"\n"+owner+"\n"+group);
pw.close();
}
public String toString() {
return phoneNumber+"\n"+owner+"\n"+group;
}
}
Every time you create PrintWriter the file is being overwritten. Since you create a new PrintWriter for each contact, the file contains only the last contact information. What you should do is to create PrintWriter only once and use it for all contacts.
Firstly, let's create a new save method with such signature:
public void save(PrintWriter writer)
I have also used the lowercase name of the method due to Java naming convention.
Now the implementation of save method will look like this:
writer.println(phoneNumber);
writer.println(owner);
writer.println(group + "\n\n\n");
Then we should replace the usage of Save method with the new one. Here is your code:
String fileName = scanner.next();
File f = null;
for (int i = 0; i < val; i++) {
if(i == 0) {
f = new File(fileName);
contacts[0].Save(fileName);
} else {
contacts[i].Save(f);
}
}
In order to fix the issue we can change it like this:
String fileName = scanner.next();
File file = new File(fileName);
try (PrintWriter writer = new PrintWriter(file)) {
for (int i = 0; i < val; i++) {
contacts[i].save(writer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I have also used try-with-resources which closes the PrintWriter automatically.
From the Javadoc of the constructor of PrintWriter:
public PrintWriter(File file)
Parameters: file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
In the Save function you create a PrintWriter everytime. So everytime the file is truncated, and then you lose the contact you saved before.
Since File I/O classes in java use Decorator Design pattern, you can use a FileWriter to take advantage of appending to a file. So you can use this code for Save() method :
public void Save(String fileName) {
File f = new File(fileName+".txt");
try {
//System.out.println("File created"); You don't need to create new file.
FileWriter fw=new FileWriter(f,true):// second argument enables append mode
pw = new PrintWriter(fw); //יצירת מדפסת לקובץ
pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");
} catch (IOException e) {
e.printStackTrace();
}
pw.close();
}
I am writing a program where I create an ArrayList, and I want to traverse the list with an iterator:
ArrayList<Person> flightAttendants = new ArrayList<Person>();
Iterator<Person> itr = flightAttendants.iterator();
Here is how I am trying to traverse the elements of the arraylist:
I have defined a toString method too:
while(itr.hasNext())
{
System.out.println(itr.next());
}
public String toString()
{
System.out.println("name of the passenger : "+name);
System.out.println("Age of the passenger : "+age);
System.out.println("Seat number of the passenger : "+seatNumber);
return "\n";
}
Whenever I try to run it, it gives me the error: java.util.ConcurrentModificationException
Where is the error here?
Update: here is the full code:
import java.util.*;
import java.io.*;
class Person
{
Integer age;
String name;
String seatNumber;
Integer fare;
int pnr;
Person()
{
try
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the name of the passenger");
name = b.readLine();
System.out.println("Enter the age of the passenger");
age = Integer.parseInt(b.readLine());
System.out.println("Enter the Seat Number you want");
seatNumber = b.readLine();
pnr = (int)(Math.random()*100000000);
System.out.println("PNR number of the passenger is : "+pnr);
}
catch(Exception e)
{
System.out.println("");
}
}
public String toString()
{
System.out.println("name of the passenger : "+name);
System.out.println("Age of the passenger : "+age);
System.out.println("Seat number of the passenger : "+seatNumber);
return "\n";
}
}
class EconomyPassenger extends Person
{
}
class BusinessPassenger extends Person
{
}
class Crew extends Person
{
}
public class Airline
{
public static void main(String[] args)
{
ArrayList<Person> flightAttendants = new ArrayList<Person>();
Iterator<Person> itr = flightAttendants.iterator();
while(true)
{
try
{
System.out.println("Welcome to Indigo!!!");
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your Choice");
System.out.println("1.Book Tickets");
System.out.println("2.Check Reservation");
System.out.println("3.Update Tickets");
System.out.println("4.Exit");
int choice=Integer.parseInt(b.readLine());
if(choice<0 || choice>4)
{
throw new InvalidChoiceException("Enter a valid choice between 1 and 4");
}
switch(choice)
{
case 1: System.out.println("\n\n1.Economy*******2.Business*******3.Crew Login*******4.Exit");
// BufferedReader c = new BufferedReader(new InputStreamReader(System.in));
int c = Integer.parseInt(b.readLine());
if(c==1)
{
flightAttendants.add(new EconomyPassenger());
}
else if(c==2)
{
flightAttendants.add(new BusinessPassenger());
}
else if(c==3)
{
flightAttendants.add(new Crew());
}
else if(c==4)
{
break;
}
break;
case 2: // System.out.println("Enter your PNR Number : ");
// int p = Integer.parseInt(b.readLine());
// System.out.println(p);
while(itr.hasNext())
{
System.out.println(itr.next());
}
break;
case 3: System.out.println("case 3");break;
case 4: return;
default: System.out.println("default");
}
}
catch(InvalidChoiceException ic)
{
// System.out.println(ic);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class InvalidChoiceException extends Exception
{
InvalidChoiceException()
{}
InvalidChoiceException(String msg)
{
System.out.println(msg);
}
}
The code being provided by you should work fine as I have tried it. Unless you show there is something else your code is working upon we cant further try to solve. I suggest you the check the question Iterators and the concurrentmodificationexception also for better understanding that your code may be somewhere falling into errors mentioned there.
As mentioned by Andrew bring the iterator into your while loop and thats working fine check now. I tried it.
The following code is two methods, one for saving to a file using object serialization and one for loading and deserializing the saved file for the user to read:
private void SaveDeck() throws Exception {
ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
fout = new FileOutputStream(filePath, true);
oos = new ObjectOutputStream(fout);
oos.writeObject(theDeck);
} catch (Exception ex) {
ex.printStackTrace();
}finally {
if(oos != null){
oos.close();
}
}
}
private FlashCardDeck[] loadDeck(){
user.setDeckMade(true);
try {
FileInputStream fis = new FileInputStream(filePath);
ObjectInputStream in = new ObjectInputStream(fis);
this.theDeck = (FlashCardDeck[])in.readObject();
in.close();
}
catch (Exception e) {
System.out.println(e);
}
return theDeck;
}
The error I'm getting is on the load method:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: myPackage.UserInterface
Saving works fine; I've opened up the .ser file after the SaveDeck method has executed and everything seemed to check out properly.
My question is if the problem is with the file itself, the save method, or external methods? I have made sure that everything not serializable (Namely, the Scanner class) is transient.
package myPackage.FlashCards;
import java.io.Serializable;
public class FlashCardDeck implements Serializable{
private static final long serialVersionUID = -1176413113990886560L;
public FlashCard[] theDeck;
public String deckName;
public FlashCardDeck(int cards, String name) {
this.deckName = name;
theDeck = new FlashCard[cards];
for (int i = 0; i < theDeck.length; i++) {
theDeck[i] = new FlashCard(i);
}
}
public String getQuestion(int i) {
return theDeck[i].QuestionToString();
}
public String getAnswer(int i ) {
return theDeck[i].AnswerToString();
}
public String getName() {
return deckName;
}
public int getDeckSize() {
return theDeck.length;
}
}
package myPackage.FlashCards;
import java.io.Serializable;
import java.util.Scanner;
public class FlashCard implements Serializable{
private static final long serialVersionUID = -8880816241107858648L;
private transient Scanner in = new Scanner(System.in);
String question;
String answer;
public FlashCard(int i) {
setCard(i);
}
public void setCard(int cards) {
System.out.println("What is the question for number " + (cards + 1) + "?");
question = in.nextLine();
System.out.println("What is the answer for number " + (cards + 1) + "?");
answer = in.nextLine();
}
public String QuestionToString() {
return "Question: " + question;
}
public String AnswerToString() {
return "Answer: " + answer;
}
}
package myPackage.FlashCards;
import java.io.Serializable;
import java.util.InputMismatchException;
import java.util.Scanner;
public class UserInterface implements Serializable{
private static final long serialVersionUID = 7755668511730129821L;
private int moreThanOnce = 0;
boolean deckMade = false;
private transient Scanner in = new Scanner(System.in);
public int AmountOfDecks() {
int decks;
System.out.println("How many decks will you be creating? (Type the number,
not the word. Ex: 2)");
decks = in.nextInt();
while (decks <= 0) {
System.out.println("You can't have less than one deck! Try again.");
decks = in.nextInt();
}
return decks;
}
public int StartMenu() {
int choice = 0;
moreThanOnce++;
if (moreThanOnce > 1) {
choice = SecondMenu();
} else {
System.out.println("\nFlash Card Creation Engine Ver. 2.5 ALPHA");
System.out.println("Press the cooresponding number for your
choice.");
System.out.println("1. Make a deck of flash cards");
System.out.println("2. Play flash cards");
System.out.println("3. Quit \n");
try { choice = in.nextInt(); } catch (InputMismatchException ime) {}
}
return choice;
}
public int AmountOfCards(int cards) {
int catchMe;
deckMade = true;
System.out.println("How many cards would you like? (Type the number, not the
word. Ex: 2)");
try {
catchMe = in.nextInt();
while (catchMe <= 0) {
System.out.println("You can't have less than one card! Try
again!");
catchMe = in.nextInt();
}
} catch (Exception ime) {
System.out.println("Uh-oh, you did that wrong! Let's try that again.
Try typing: 3");
cards = 0;
catchMe = in.nextInt();
}
cards = catchMe;
return cards;
}
public boolean getDeckMade() {
return deckMade;
}
public void setDeckMade(boolean makeDeckMade) {
this.deckMade = makeDeckMade;
}
public String NameOfDeck() {
String name;
System.out.println("What would you like to name this deck?");
name = in.next();
return name;
}
private int SecondMenu() {
int choice = 0;
System.out.println("Now what would you like to do?");
if (deckMade) {
System.out.println("1. Make or load a deck of flash cards -- DONE");
} else {
System.out.println("1. Make a deck of flash cards.");
}
System.out.println("2. Play flash cards");
System.out.println("3. Quit \n");
try { choice = in.nextInt(); } catch (InputMismatchException ime) {}
return choice;
}
public boolean SetMode() {
boolean timed = false;
int userChoice = 0;
while (userChoice < 1 || userChoice > 2) {
System.out.println("What mode are you selecting?");
System.out.println("1. Timed");
System.out.println("2. Normal");
System.out.println("3. Help");
System.out.println("4. Quit");
userChoice = in.nextInt();
if (userChoice == 1) {
timed = true;
} else if (userChoice == 3) {
System.out.println("Timed: Answers to a flash card will
appear after a set amount of seconds, then show the next
question after the same amount of seconds, which are set by
the user (that's you!)");
System.out.println("Normal: Answers to a flash card will
appear when the user (also you!) presses enter, and wait for
enter to be pressed before showing the next question.");
} else if (userChoice == 4) {
System.out.println("Have a good day.");
System.exit(0);
} else {
System.out.println("Choose from the proivded list -- 1 for
Timed mode, 2 for Normal mode, 3 to show the Help menu, 4 to
quit.");
System.out.println();
}
}
return timed;
}
public String setQuestion(int cards) {
String question = "";
return question;
}
public String setAnswer(int cards) {
String answer = "";
return answer;
}
}
The class you're trying to serialize (and any non-transient objects referenced by that class) must implement the Serializable interface.
judging by the error you have a UserInterface class referenced there which is not serializable.
Edit:
Also
new FileOutputStream(filePath, true);
always appends to the end of the file instead of clearing the file. You may have older data in the file that is not deserialized correctly. You could try removing the file and trying again.
In general - appending different objects to a file may be a bad choice considering data corruption. If different files for each deck are not an option, I might go for a separate DeckStore object that holds all the decks and gets serialized as a whole.
Class that you want to serialize should implement Serializable interface
public class FlashCardDeck implements Serializable {
// Fields and methods of the class ...
}
The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
This is a workout app that I'm working on. The idea is to create an account(text file) and store the data that you enter inside it. Here's what I have so far.
public static void main(String[] args) {
boolean start = true;
while (start == true) {
CreateNewMember();
start = DecideToAddOrQuit();
}
}
public static void CreateNewMember() {
Scanner keyboard = new Scanner(System.in);
out.println("Enter a username: ");
String input = keyboard.nextLine();
createMember member = new createMember(input);
member.setMembership();
member.setInfo();
}
public static boolean DecideToAddOrQuit() {
Scanner keyboard = new Scanner(System.in);
out.println("\nPress 1 if you want to continue adding data.");
out.println("Press any other key if you want to leave.");
String decision = keyboard.nextLine();
if (decision.equals("1")) {
out.println("");
return true;
} else {
out.println("Goodbye!");
return false;
}
}
And here's the class responsible for adding data to the file:
public class createMember {
public String name;
private String fullName;
private String age;
private String experience;
private Formatter x;
public createMember(String name) {
this.name = name;
}
public void setMembership() {
try {
x = new Formatter(name);
out.println("File with name \"" + name + "\" has been created!");
} catch (Exception e) {
out.println("Could not create username.");
}
}
public void setInfo () {
Scanner keyboard = new Scanner(System.in);
String fullNameIn, ageIn, experienceIn;
out.println("Enter your Full Name");
fullNameIn = keyboard.nextLine();
fullName = fullNameIn;
out.println("Enter your Age");
ageIn = keyboard.nextLine();
age = ageIn;
out.println("Enter your lifting experience\n");
experienceIn = keyboard.nextLine();
experience = experienceIn;
x.format("%s\t%s\t%s", fullName, age, experience );
}
}
The values that I enter(fullName, age, experience) are NOT stored in the username file. How do I fix this and why is it occuring?
If you are expecting output to be written as the program is running, you may not see it because Formatter buffers the output.
You must close() the file when you are done with it (x.close()) so that any remaining buffered data is written (this does not happen automatically, even on program exit). Also if you want the output to actually be written immediately, flush() it as soon as you write a line (x.flush()).
This question is not the clearest, but as far is I'm concerned you haven't ever told anything to actually write the data to a file at all. You should use PrintWriter. This will load the data you want into the file. Plus, in your code, your file is never created.
import java.io.PrintWriter;
public class createMember {
public String name;
private String fullName;
private String age;
private String experience;
// private Formatter x; not quite sure what this does. There seems to be no need for it.
PrintWriter write;
File f;
public createMember(String name) {
this.name = name;
}
public void setMembership() throws Exception {
try {
// x = new Formatter(name);
f = new File (name);
f.createNewFile(); // This throws a HeadlessException (i believe, as it might be a FileNotFoundException instead)
out.println("File with name \"" + name + "\" has been created!");
} catch (Exception e) {
out.println("Could not create username.");
}
}
public void setInfo () throws Exception {
Scanner keyboard = new Scanner(System.in);
String fullNameIn, ageIn, experienceIn;
write = new PrintWriter(f.toString()); // This throws a FileNotFoundException
out.println("Enter your Full Name");
fullNameIn = keyboard.nextLine();
fullName = fullNameIn;
write.println (fullName);
out.println("Enter your Age");
ageIn = keyboard.nextLine();
age = ageIn;
write.println(age);
out.println("Enter your lifting experience\n");
experienceIn = keyboard.nextLine();
experience = experienceIn;
write.println(experience);
//x.format("%s\t%s\t%s", fullName, age, experience );
write.close(); // Be sure to close it, or it gives a warning and the file is never written.
}
}
I hope this is what you're looking for and happy coding!