possible already open file error; halted - java

So, when I run this, I get no exceptions, but the execution halts. I entered a few lines of code to see where the hault is coming from. On initial execution, it creates a file in the path given in the Customer class. Once I do one of the actions, it doesn't let me go past the first debugging line. Ideas?
Heres the application:
package javaapplication18.pkg3;
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication183 {
/**
* #param args the command line arguments
*/
static boolean keepGoing = true;
public static void main(String[] args) {
System.out.println("Welcome to the Customer Maintenance application");
//keepGoing = true;
Scanner sc = new Scanner(System.in);
while (keepGoing){
displayMenu();
String userChoice = getRequiredString("Enter a command: ", sc);
System.out.println("DEBUG LINE 1");
CustomerTextFile textFile = new CustomerTextFile();
System.out.println("DEBUG LINE 2");
performAction(userChoice, textFile);
System.out.println("DEBUG LINE 3");
}
// TODO code application logic here
}
public static void displayMenu() {
System.out.println();
System.out.println("COMMAND MENU");
System.out.println("list - List all customers");
System.out.println("add - Add a customer");
System.out.println("del - Delete a customer");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application");
System.out.println();
}
public static void performAction(String choice, CustomerTextFile textFile){
Scanner sc = new Scanner(System.in);
switch (choice.toLowerCase()) {
case "list":
//action
ArrayList<Customer> currentList = textFile.getCustomers();
for (Customer c : currentList) {
System.out.print(c.getEmail() + "\t");
System.out.print(c.getFirstName() + "\t");
System.out.println(c.getLastName());
}
break;
case "add":
String email = getRequiredString("Enter customer email address:", sc);
String firstName = getRequiredString("Enter first name:", sc);
String lastName = getRequiredString("Enter last name:", sc);
Customer c = new Customer(email, firstName, lastName);
textFile.addCustomer(c);
System.out.println(firstName + lastName + " was added to the database.");
break;
case "del":
String deleteUserByEmail = getRequiredString("Enter customer email to delete:", sc);
Customer delCustomer = textFile.getCustomer(deleteUserByEmail);
textFile.deleteCustomer(delCustomer);
break;
case "help":
//displayMenu();
break;
case "exit":
keepGoing = false;//exit();
break;
default:
System.out.println("You entereed something not in the list. Please try again.");
System.out.println();
}
}
public static boolean exit(){
System.out.println("Exit");
return false;
}
public static String getRequiredString(String prompt, Scanner sc) {
String s = "";
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
s = sc.nextLine();
if (s.equals(""))
System.out.println("Error! This entry is required. Try again.");
else
isValid = true;
}
return s;
}
}
Here is the CustomerTextFile class:
package javaapplication18.pkg3;
import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;
public class CustomerTextFile implements CustomerDAO{
private ArrayList<Customer> customers = null;
private Path customersPath = null;
private File customersFile = null;
public CustomerTextFile(){
customersPath = Paths.get("customers.txt");
customersFile = customersPath.toFile();
customers = this.getCustomers();
}
#Override
public Customer getCustomer(String emailAddress) {
for (Customer c : customers) {
if (c.getEmail().equals(emailAddress))
return c;
}
return null;
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public ArrayList<Customer> getCustomers() {
if (customers != null)
return customers;
customers = new ArrayList<>();
if (!Files.exists(customersPath)) {
try {
Files.createFile(customersPath);
}
catch (IOException e) {
return null;
}
}
if (Files.exists(customersPath)) {
try (BufferedReader in = new BufferedReader(new FileReader(customersFile))){
String line = in.readLine();
while(line != null) {
String[] columns = line.split("\t");
String email = columns[0];
String firstName = columns[1];
String lastName = columns[2];
Customer c = new Customer(email, firstName, lastName);
customers.add(c);
}
}
catch (IOException e) {
System.out.println(e);
return null;
}
}
return customers;
}
#Override
public boolean addCustomer(Customer c) {
customers.add(c);
return this.saveCustomers();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public boolean updateCustomer(Customer c) {
Customer oldCustomer = this.getCustomer(c.getEmail());
int i = customers.indexOf(oldCustomer);
customers.remove(i);
customers.add(i, c);
return this.saveCustomers();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public boolean deleteCustomer(Customer c) {
customers.remove(c);
return this.saveCustomers();
}
private boolean saveCustomers() {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(customersFile)))){
for (Customer customer : customers) {
out.print(customer.getEmail() + "\t");
out.print(customer.getFirstName() + "\t");
out.println(customer.getLastName());
}
out.close();
return true;
}
catch (IOException e) {
return false;
}
}
}
Im not certain if the problem is in the application or if it is in the textfile class
run:
Welcome to the Customer Maintenance application
COMMAND MENU
list - List all customers
add - Add a customer
del - Delete a customer
help - Show this menu
exit - Exit this application
list
DEBUG LINE 1
Above was an example of the console output.

Why are you declaring a string inside the loop?
try this instead:
Scanner sc = new Scanner(System.in);
String userChoice;
do {
displayMenu();
userChoice = sc.nextLine(); //takes in the entire lien you type in
System.out.println("DEBUG LINE 1");
CustomerTextFile textFile = new CustomerTextFile();
System.out.println("DEBUG LINE 2");
performAction(userChoice, textFile);
System.out.println("DEBUG LINE 3");
} while(keepGoing);
Hope this helps

Related

It keeps me looping even though I don't have any loops

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'.

java.util.ConcurrentModificationException Error while trying to use iterator

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.

DeSerialized Object containing ArrayList has all null values

Hopefully someone can provide some insight on this issue. I have created an instance of an object that contains an ArrayList of information (username, password, password hint). I am trying to serialize the object. It looks like it is serializing properly, but when I restart the project to deserialize, it returns null values in the ArrayList. Why is it returning null values for the ArrayList objects?
Driver Class:
import java.io.Serializable;
public class TestingDriver implements Serializable{
private static final long serialVersionUID = 12345L;
private static TestingAccount users = new TestingAccount();
public static void main(String[] args) {
int foreverLoop = 0;
users = DeSerialize.main();
while (foreverLoop < 1) {
int selection = users.displayMainMenu();
if (selection == 1) {
users.listUsers();
}
else if (selection == 2) {
users.addUser();
}
else if (selection == 3) {
users.deleteUser();
}
else if (selection == 4) {
users.getPasswordHint();
}
else if (selection == 5) {
Serialize.main(users);
System.exit(0);
}
else {
System.out.println("That option does not exist. Please try again.");
}
}
}
}
TestingUser Class (objects of this class will populate the ArrayList):
import java.io.Serializable;
public class TestingUser extends UserAccount implements Serializable, Comparable <TestingUser> {
private static final long serialVersionUID = 12345L;
public TestingUser(String username, String password, String passwordHint) {
super(username, password, passwordHint);
}
public TestingUser() {
}
#Override
public void getPasswordHelp() {
System.out.println("");
System.out.println("Password hint: " + passwordHint);
System.out.println("");
}
#Override
public int compareTo(TestingUser otherAccount) {
if (this.username.compareToIgnoreCase(otherAccount.username) < 0) {
return -1;
}
else if (this.username.compareToIgnoreCase(otherAccount.username) > 0) {
return 1;
}
else {
return 0;
}
}
}
TestingAccount class (calling this class creates an object that contains the ArrayList):
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Scanner;
public class TestingAccount implements Serializable {
private static final long serialVersionUID = 12345L;
public ArrayList<TestingUser> userList;
private String username;
private String password;
private String passwordHint;
public TestingAccount() {
userList = new ArrayList<TestingUser>();
}
public void listUsers() {
for (int i=0; i<this.userList.size(); i++) {
System.out.println(this.userList.get(i));
}
}
#SuppressWarnings("resource")
public void addUser() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a username: ");
username = input.next();
TestingUser tempAccount = new TestingUser(username, null, null);
if (this.userList.contains(tempAccount) == true) {
System.out.println("This user already exists.");
}
else {
System.out.println("Please enter a password: ");
password = input.next();
System.out.println("Please enter a password hint: ");
passwordHint = input.next();
tempAccount.password = password;
tempAccount.passwordHint = passwordHint;
this.userList.add(tempAccount);
System.out.println("Account " + tempAccount.username + " has been added.");
}
}
#SuppressWarnings("resource")
public void deleteUser() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the username to be deleted: ");
username = input.next();
TestingUser tempAccount = new TestingUser(username, null, null);
if (this.userList.contains(tempAccount) == true) {
int actIndex = this.userList.indexOf(tempAccount);
System.out.println("Please enter the password: ");
password = input.next();
tempAccount.password = password;
boolean passwordGood = this.userList.get(actIndex).CheckPassword(tempAccount);
int accountIndex = this.userList.indexOf(tempAccount);
tempAccount = this.userList.get(accountIndex);
if (passwordGood == true) {
this.userList.remove(actIndex);
System.out.println("The account has been deleted.");
}
else {
System.out.println("The password is not correct.");
}
}
else {
System.out.println("The account does not exist.");
}
}
#SuppressWarnings("resource")
public void getPasswordHint() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a username: ");
username = input.next();
TestingUser tempAccount = new TestingUser(username, null, null);
if (this.userList.contains(tempAccount) == true) {
int actIndex = this.userList.indexOf(tempAccount);
tempAccount = this.userList.get(actIndex);
System.out.println("The password hint isL: " + tempAccount.passwordHint);
}
else {
System.out.println("The account does not exist.");
}
}
#SuppressWarnings({ "resource" })
public int displayMainMenu() {
int selection = 0;
Scanner input = new Scanner(System.in);
System.out.println("");
System.out.println("System Menu:");
System.out.println("1. List Users");
System.out.println("2. Add User");
System.out.println("3. Delete User");
System.out.println("4. Get Password Hint");
System.out.println("5. Quit");
System.out.println("");
System.out.println("What would you like to do?");
selection = input.nextInt();
return selection;
}
}
Serialize class:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Serialize {
public static void main(TestingAccount users) {
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("serialize"));
oos.writeObject(users);
oos.close();
} catch (FileNotFoundException e1) {
System.err.println("File not found.");
} catch (IOException e2) {
System.err.println("Unable to serialize.");
e2.printStackTrace();
}
}
}
Deserialize class:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeSerialize {
public static TestingAccount main() {
TestingAccount deSerialize = null;
try {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("serialize"));
deSerialize = (TestingAccount) ois.readObject();
ois.close();
} catch (FileNotFoundException e1) {
System.err.println("Unable to open file.");
} catch (IOException e2) {
System.err.println("Could not de-serialize.");
e2.printStackTrace();
} catch (ClassNotFoundException e3) {
System.err.println("Could not cast to class TestingAccount.");
}
return deSerialize;
}
}
It looks like UserAccount isn'tSerializable. So when you serialize the derived TestingUser class, none of the UserAccount data gets serialized. See Object Serialization Specification #2.1.13(a). TestingUser doesn't have any instance state of its own to serialize.
The solution is to make UserAccount implement Serializable.
Not sure why this comes as a surprise.

Scanner not working properly

Hello again fellow programmers. I have another problem that's puzzling me. I am trying to receive input from a user but always receive an "java.util.NoSuchElementException: No line found". I have tried all the methods I've searched with no luck. Here is my code:
import java.util.Scanner;
import java.io.*;
public class UserLog {
static String username;
static String password;
static String passcompare;
static File name;
static String Userfile = "username-";
static String Passfile = "password-";
public static void main(String[] args) {
menu();
}
public static void menu(){
boolean call = false;
try (Scanner in = new Scanner(System.in)) {
do {
System.out.println("Select an option: ");
System.out.println("1: New account \n"
+ "2: Existing account");
System.out.print("-");
int choice = in.nextInt();
in.nextLine();
switch(choice) {
case 1:
call = true;
System.out.println("\nNew account called\n");
userCreate();
break;
case 2:
call = true;
System.out.println("\nExisting account called\n");
login();
break;
default:
System.out.println("\nNot a valid option\n");
}
} while(!call);
in.close();
}
catch(Exception ex) {
System.out.println("Exception Text: " + ex);
}
}
static void login(){
try (Scanner in = new Scanner(System.in)) {
System.out.println("LOGIN SCREEN\n");
System.out.print("Username: ");
username = in.nextLine();
name = new File("user-" + username + ".txt");
if(name.exists()) {
System.out.println("Username exists");
System.out.print("Password: ");
password = in.nextLine();
//scans userfile for password
if(password.length() != 0 && password.length() >= 8 /* and password-username match */) {
System.out.println("Login successful");
in.close();
}
}
else {
System.out.println("Username doesn't exist in system");
System.out.println("Would you like to create this user? (y/n)");
System.out.print("-");
char choice = (char)System.in.read();
switch(choice) {
case 'Y':
case 'y':
System.out.println("Creating user " + username);
name = new File("user-" + username + ".txt");
name.createNewFile();
System.out.println("User created");
passCreate(name);
in.close();
break;
case 'N':
case 'n':
System.out.println("Denied creation of user");
in.close();
break;
default:
System.out.println();
}
}
in.close();
} catch (IOException ex) {
System.out.println("Exception Text: " + ex);
}
}
private static File nameCreate() {
try (Scanner user = new Scanner(System.in)) {
System.out.print("Enter Username: ");
username = user.nextLine();
name = new File("user-" + username + ".txt");
if(!name.exists()) {
name.createNewFile();
try (FileWriter fw = new FileWriter(name)) {
fw.write(Userfile + username + "\n");
fw.write(Passfile);
fw.flush();
fw.close();
}
catch(Exception ex) {
System.out.println("Exception Text: " + ex);
}
//puts lines of text in the file-
//username-"username"
//password-
//
System.out.println("User Created\n");
}
else if(name.exists()) {
System.out.println("User already exists\n");
nameCreate();
}
user.close();
}
catch(Exception ex) {
System.out.println("Exception Text: " + ex);
}
return name;
}
private static void passCreate(File user) {
username = user.toString();
System.out.println(username + "\n");
boolean code = false;
try (Scanner pass = new Scanner(System.in)) {
do{
//opens file and reads until line "password-" and appends it with created password once confirmed
System.out.println("Create a password");
System.out.print("Password: ");
password = pass.nextLine();
if(password.length() >= 8) {
System.out.print("Confirm Password: ");
passcompare = pass.nextLine();
if(password.equals(passcompare)) {
code = true;
System.out.println("Passwords match\n");
//stores password
}
else {
System.out.println("Passwords don't match\n");
}
}
else {
System.out.println("Password needs to be longer than 8 characters\n");
}
}while(!code);
pass.close();
}
catch(Exception ex) {
System.out.println("Exception Text: " + ex);
}
}
private static void userCreate() {
nameCreate();
passCreate(name);
}
}
It's ugly and incomplete, I know, but this problem has kept me from going further. I am able to get to the password creation if I go through existing user option and create a user that way, but if I try to go through the create new user, I get the no line exception. My question is: how do I create more lines for the scanner to use to be able to create a password, or what other options do I have for completing this task. I've tried hasNextLine() and that's what made me realize that there are no more lines. Thanks
Closing the Scanner instances causes the underlying InputStream to be closed and causes a NoSuchElementException to be thrown on subsequent reads. There's no need to close Scanner unless you wish subsequent reads to fail.
Create a single Scanner instance are use for all methods.
Don't close Scanner
Java is an OO language. Use non-static methods.
The result:
public class UserLog {
private String username;
// more variables...
private final Scanner in;
public UserLog() {
in = new Scanner(System.in);
}
public static void main(String[] args) {
UserLog userLog = new UserLog();
userLog.showMenu();
}
public void menu() {
boolean call = false;
do {
try {
System.out.println("Select an option: ");
System.out.println("1: New account \n" + "2: Existing account");
System.out.print("-");
int choice = in.nextInt();
in.nextLine();
switch (choice) {
case 1:
call = true;
System.out.println("\nNew account called\n");
userCreate();
break;
case 2:
call = true;
System.out.println("\nExisting account called\n");
login();
break;
default:
System.out.println("\nNot a valid option\n");
}
} catch (InputMismatchException e) {
System.out.println("Invalid option " + in.nextLine());
}
} while (!call);
}
...
}

How to Serialize an ArrayLIst in java without getting errors?

I am just trying to output a previously created ArrayList to serialise it for future storage.
but when I attmept to do so I get the runTime error "notSerialisableException: Department.
Is their a speicial way of serializing an arrayList??
Would someone be able to tell me why I may be getting this error.
This is the code:
import java.awt.*;
import java.util.*;
import java.io.*;
import java.io.Serializable;
public class tester1ArrayListObjectSave
{
private ArrayList <Department> allDeps = new ArrayList<Department>();
private int choice = 0;
private String name;
private String loc;
Department theDepartment;
Scanner scan;
public static void main(String[] args)
{
new tester1ArrayListObjectSave();
}
public tester1ArrayListObjectSave()
{
scan = new Scanner(System.in);
options();
}
public void options()
{
System.out.println("wadya wanna do");
System.out.println("1. create a new department");
System.out.println("2. read from text file");
System.out.println("4. save it to system as a serializable file");
System.out.println(". read from text file");
System.out.println("3. to exit");
choice = scan.nextInt();
workOutOptions();
}
public void workOutOptions()
{
if (choice ==1)
{
createNewEmp();
}
else if (choice ==2)
{
try
{
readTextToSystem();
}
catch (IOException exc)
{
System.out.println("uh oh their was an error: "+exc);
}
}
else if (choice == 3)
{
System.exit(0);
}
else if (choice ==4)
{
try
{
createSerialisable();
}
catch (IOException exc)
{
System.out.println("sorry could not serialise data cause of this:"+exc);
}
}
else
{
System.out.println("do nothing");
}
}
public void createNewEmp()
{
System.out.println("What is the name");
name = scan.next();
System.out.println("what is the chaps loc");
loc = scan.next();
try
{
saveToSystem();
}
catch (IOException exc)
{
// do something here to deal with problems
}
theDepartment = new Department(name,loc);
allDeps.add(theDepartment);
options();
}
public void saveToSystem() throws IOException
{
FileOutputStream fos = new FileOutputStream( "backUp.txt", true );
PrintStream outFile = new PrintStream(fos);
System.out.println("added to system succesfully");
outFile.println(name);
outFile.println(loc);
outFile.close();
options();
}
public void readTextToSystem() throws IOException
{
Scanner inFile = new Scanner ( new File ("backUp.txt") );
while (inFile.hasNextLine())
{
name=inFile.nextLine();
System.out.println("this is the name: "+name);
loc = inFile.nextLine();
System.out.println("this is the location: "+loc);
Department dDepartment = new Department(name,loc);
allDeps.add(dDepartment);
options();
}
System.out.println(allDeps);
}
public void createSerialisable() throws IOException
{
FileOutputStream fileOut = new FileOutputStream("theBkup.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allDeps);
options();
}
}
ArrayList isn't the problem; your Department object is.
You need to implement the Serializable interface in that object.

Categories

Resources