how to fix up code with java display - java

import java.util.Scanner;
import java.util.Formatter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
class Enrolment{
public static void main(String[] args)
{
System.out.println("/*-------------------------------------");
System.out.println("My name: XIANGYU QIAO");
System.out.println("My student number: 5089864");
System.out.println("My email address: xq907#uowmail.edu.au");
System.out.println("Assignment number: 2");
System.out.println("-------------------------------------*/");
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
class Student{
private static Formatter outStream;
private static Scanner inStream;
public Student() throws IOException
{
outStream = new Formatter(new File("student1.txt"));
String fullName = "David Black";
String email = "davblk#ipw.edu.au";
String course = "1853E";
sNumber = 375428;
outStream.format("%s %s %s %i", fullName, email, course, sNumber);
outStream.close();
inStream = new Scanner( new File("student1.txt"));
String Fullname = inStream.next();
String Email = inStream.next();
String Course = inStream.next();
int Studentnumber = inStream.nextInt();
inStream.close();
}
public void displayStudInfo()
{
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
}
}
class Subject{
private static Formatter outStream;
private static Scanner inStream;
public Subject() throws IOException
{
outStream = new Formatter(new File("subject1.txt"));
String sCode = "CSIT455";
String session = "Autmn";
int year = 2017;
outStream.format("%s %s %i", sCode, session, year);
outStream.close();
inStream = new Scanner( new File("subject1.txt"));
String Subjectcode = inStream.next();
String Session = inStream.next();
int Year = inStream.nextInt();
inStream.close();
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
i am trying to create a file of student information and display it but i could not find a way to do that. could anyone help me to fix the code?
i am asked to display the student information in class Enrolment(main method here)and subject information that is given in class Student and Subject.i have no idea how to link these three things though it requires to use displayStudInfo method in class Student and displaySubjectInfo in class Subject.

If I correctly understand, you cannot access properties from constructor in displayStudInfo method. So assigning those properties to class properties will resolve the issue.
class Student {
private final String fullname;
private final String email;
private final String course;
private final int studentNumber;
public Student() throws IOException {
writeStudent();
Scanner inStream = new Scanner(new File("student1.txt"));
fullname = inStream.next();
email = inStream.next();
course = inStream.next();
studentNumber = inStream.nextInt();
inStream.close();
}
private void writeStudent() throws FileNotFoundException {
Formatter outStream = new Formatter(new File("student1.txt"));
outStream.format("%s %s %s %i", "David Black", "davblk#ipw.edu.au", "1853E", 375428);
outStream.close();
}
public void displayStudInfo() {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}
}
If you do not want to add any more class prop, you will need to ad arguments to your method:
public void displayStudInfo( String fullname,String email,String course, int studentNumber) {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}

Related

Is there a way to access the date added to an ArrayList in a different to change its data?

I have this in the Class: public static ArrayList<String> studentInfo = new ArrayList<String>();I created a method CreateStudent() that basically allows the user to create a student using Scanner, the DisplayStudent() uses ObjectInputStream to open the file and read the data. Now, when the users creates a student, it stores the data into an ArrayList using studentInfo.add(), the idea is that the EditStudent() access the data added into the ArrayList with the info added in CreateStudent() Is there a way to access that list from another method?I would appreciate any ideas, here is my code:
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.*;
import java.lang.ClassNotFoundException;
public class MidTermProject extends ObjectOutputStream {
private boolean append;
private boolean initialized;
private DataOutputStream dout;
static AtomicInteger idGenerator = new AtomicInteger(0001);
static int id;
public static String FullName;
public static String address;
public static String city;
public static String state;
public static String className;
public static String instructor;
public static String department;
public static String classNumber;
public static String courseNumber;
public static String year;
public static String semester;
public static String grade;
public static String studentID;
public static String courseID;
public static String enrollmentID;
public static ArrayList<String> studentInfo = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
protected MidTermProject(boolean append) throws IOException, SecurityException {
super();
this.append = append;
this.initialized = true;
}
public MidTermProject(OutputStream out, boolean append) throws IOException {
super(out);
this.append = append;
this.initialized = true;
this.dout = new DataOutputStream(out);
this.writeStreamHeader();
}
#Override
protected void writeStreamHeader() throws IOException {
if (!this.initialized || this.append) return;
if (dout != null) {
dout.writeShort(STREAM_MAGIC);
dout.writeShort(STREAM_VERSION);
}
}
public static int getId() {
return id;
}
///Create Student Method
public static void CreateStudent() throws IOException {
File file = new File("StudentInfo.dat");
boolean append = file.exists();
Scanner keyboard = new Scanner(System.in);
try (
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
) {
id = idGenerator.getAndIncrement();
studentID = Integer.toString(getId());
oout.writeObject("Student ID: " + studentID);
System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
FullName = keyboard.nextLine();
oout.writeObject("Full Name: " + FullName);
System.out.print("Address: ");
address = keyboard.nextLine();
oout.writeObject("Address: " + address);
System.out.print("City: ");
city = keyboard.nextLine();
oout.writeObject("City: " + city);
System.out.print("State: ");
state = keyboard.nextLine();
oout.writeObject("State: " + state + "\n");
studentInfo.add(studentID);
studentInfo.add(FullName);
studentInfo.add(address);
studentInfo.add(city);
studentInfo.add(state);
oout.close();
System.out.println("Done!\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
///Edit Student Method
public static void EditStudent() throws IOException {
String editName;
String editaddress;
String editCity;
String editState;
int editID;
String editStudent;
boolean endOfFile = false;
Scanner keyboard = new Scanner(System.in);
System.out.print(studentInfo);
System.out.print("Enter the ID of the student you would like to edit: ");
editID = keyboard.nextInt();
String editingID = Integer.toString(editID);
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
File file = new File("StudentInfo.dat");
boolean append = file.exists();
while(!endOfFile)
{
try
{
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
editStudent = (String) inputFile.readObject();
if(editingID == oout.studentID) {
System.out.print("\nPlease enter NEW information bellow.\n" + "\nFull Name: ");
editName = keyboard.nextLine();
oout.writeObject("Full Name: " + editName);
System.out.print("Address: ");
editaddress = keyboard.nextLine();
oout.writeObject(editaddress);
System.out.print("City: ");
editCity = keyboard.nextLine();
oout.writeObject(editCity);
System.out.print("State: ");
editState = keyboard.nextLine();
oout.writeObject(editState);
oout.close();
System.out.print("Successfully Edited");
} else {
System.out.print("Error");
}
}
catch (EOFException | ClassNotFoundException e)
{
endOfFile = true;
}
}
}
Display Student Method
public static void DisplayStudent() throws IOException {
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
String student;
boolean endOfFile = false;
while(!endOfFile)
{
try
{
student = (String) inputFile.readObject();
System.out.print(student + "\n");
}
catch (EOFException | ClassNotFoundException e)
{
endOfFile = true;
}
}
System.out.println("\nDone");
inputFile.close();
}

ArrayList gets overwritten everytime a new instance is created

I'm a new programmer,
I'm terribly sorry for the walls of code, but I simply can't find the error.
I am tring to create an arrayList that stores input values, but everytime I create the 2nd instance, the first instance gets overwritten. It does print two instances, but both instances have the same value.
Main block:
The problem area is at the bottom of this code, "switch sc1" and "switch s2, case 2"
package com.company;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
User user = new User(null, null, null, null, null);
Login login = new Login(null, null, null, null, null);
Stream stream = new Stream(null, null, null, null, 0, null, null);
List list = new List(null, null, null, null, 0, null, null);
ArrayList<Stream> joinableList = new ArrayList<Stream>();
ArrayList<Stream> completedList = new ArrayList<Stream>();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM-yyyy HH:mm");
boolean showRoom = false;
while (showRoom == false) {
System.out.println("\nWelcome to ShowRoom\n\nPress 1 to login\nPress 2 to create a user\n");
Scanner choice1 = new Scanner(System.in);
System.out.print("Input: ");
int s1 = choice1.nextInt();
switch (s1) {
case 1:
System.out.print("\nEnter Username: ");
Scanner scanUsername = new Scanner(System.in);
String username = scanUsername.nextLine();
user.setUsername(username);
System.out.print("\nEnter Password: ");
Scanner scanPassword = new Scanner(System.in);
String password = scanPassword.nextLine();
user.setPassword(password);
login.verifyLogin(username, password);
break;
case 2:
System.out.print("\nChoose Username: ");
Scanner scanChooseUsername = new Scanner(System.in);
username = scanChooseUsername.nextLine();
user.setUsername(username);
user.saveUsername();
System.out.print("\nChoose Password: ");
Scanner scanChoosePassword = new Scanner(System.in);
password = scanChoosePassword.nextLine();
user.setPassword(password);
user.savePassword();
break;
}
boolean loggedIn = false;
while (loggedIn == false) {
System.out.println("\nWelcome to your dashboard " + user.username + "\n\nPress 1 to create a stream\nPress 2 to view joinable streams\nPress 3 to view completed streams");
Scanner choice2 = new Scanner(System.in);
System.out.print("\nInput: ");
int s2 = choice2.nextInt();
switch (s2) {
case 1:
String listUsername = user.username;
stream.setListUsername(user.username);
Scanner chooseTitle = new Scanner(System.in);
System.out.print("\nChoose title: ");
String title = chooseTitle.nextLine();
stream.setTitle(title);
System.out.println("\nYou have chosen: " + stream.title);
Scanner chooseGenre = new Scanner(System.in);
System.out.print("\nChoose genre:\n\nPress 0 for " + stream.genreArray[0] + "\nPress 1 for " + stream.genreArray[1] + "\nPress 2 for " + stream.genreArray[2] + "\n\nInput: ");
int chosenGenre = chooseGenre.nextInt();
String genre = stream.genreArray[chosenGenre];
stream.setGenre(genre);
System.out.println("\nYou have chosen: " + stream.genre);
Scanner chooseType = new Scanner(System.in);
System.out.print("\nChoose type:\n\nPress 0 for " + stream.typeArray[0] + "\nPress 1 for " + stream.typeArray[1] + "\nPress 2 for " + stream.typeArray[2] + "\n\nInput: ");
int chosenType = chooseType.nextInt();
String type = stream.typeArray[chosenType];
stream.setType(type);
System.out.println("\nYou have chosen: " + stream.type);
Scanner choosePrice = new Scanner(System.in);
System.out.print("\nChoose price: ");
double price = choosePrice.nextDouble();
stream.setPrice(price);
System.out.println("\nYou have chosen: " + stream.price);
Scanner chooseStartTimeDate = new Scanner(System.in);
System.out.print("\nChoose start time and date: \n\nInsert time and date in this format: dd/mm-yyyy hh:mm\n\nInput: ");
String startTimeDate = chooseStartTimeDate.nextLine();
stream.setStartTimeDate(startTimeDate);
System.out.println("\nYou have chosen " + stream.startTimeDate);
Scanner chooseEndTimeDate = new Scanner(System.in);
System.out.print("\nChoose end time and date: \n\nInsert time and date in this format: dd/mm-yyyy hh:mm\n\nInput: ");
String endTimeDate = chooseEndTimeDate.nextLine();
stream.setEndTimeDate(endTimeDate);
System.out.println("\nYou have chosen " + stream.endTimeDate);
Scanner confirmStream = new Scanner(System.in);
System.out.print("\nDo you want to create a stream, with the following details?\n\nTitle: " + title + "\nGenre: " + genre + "\nType: " + type + "\nPrice: " + price + "\nStart date and time: " + startTimeDate + "\nEnd date and time: " + endTimeDate + "\n\nPress 1 to confirm\nPress 2 to go back\n\nInput: ");
int sc1 = confirmStream.nextInt();
switch (sc1) {
case 1:
list.addJoinableList(stream);
System.out.println("\nStream has been created and added to list");
loggedIn = false;
break;
case 2:
loggedIn = false;
break;
}
case 2:
list.printJoinableList();
break;
case 3:
System.out.println("\nCompleted stream list");
break;
}
}
}
}
}
Stream block:
This block is used to inherit the properties for use in the class "List"
package com.company;
import java.time.LocalDateTime;
public class Stream {
protected String listUsername;
protected String title;
protected String genre;
protected String type;
protected double price;
protected String startTimeDate;
protected String endTimeDate;
public Stream (String listUsername, String title, String genre, String type, double price, String startTimeDate, String endTimeDate) {
this.listUsername = listUsername;
this.title = title;
this.genre = genre;
this.type = type;
this.price = price;
this.startTimeDate = startTimeDate;
this.endTimeDate = endTimeDate;
}
String genreArray[] = {"Comedy", "Lifestyle", "Music"};
String typeArray[] = {"Entertainment", "Familiy", "Work"};
public String getListUsername() { return listUsername; }
public void setListUsername(String listUsername) { this.listUsername = listUsername; }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getStartTimeDate() {
return startTimeDate;
}
public void setStartTimeDate(String startTimeDate) {
this.startTimeDate = startTimeDate;
}
public String getEndTimeDate() { return endTimeDate; }
public void setEndTimeDate(String endTimeDate) { this.endTimeDate = endTimeDate;}
}
List block:
I think that the main issues are here, but I just can't figure out what is wrong.
package com.company;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class List extends Stream {
public List(String listUsername, String title, String genre, String type, double price, String startTimeDate, String endTimeDate) {
super(listUsername, title, genre, type, price, startTimeDate, endTimeDate);
}
ArrayList<Stream> joinableList = new ArrayList<Stream>();
ArrayList<Stream> completedList = new ArrayList<Stream>();
public void addJoinableList(Stream stream) {
joinableList.add(stream);
}
public void printJoinableList() {
for (Stream s : joinableList) {
System.out.print("\nUsername: " + s.getListUsername());
System.out.print("\nTitle: " + s.getTitle());
System.out.print("\nGenre: " + s.getGenre());
System.out.print("\nType: " + s.getType());
System.out.print("\nPrice: " + s.getPrice());
System.out.print("\nStart time and date: " + s.getStartTimeDate());
System.out.print("\nEnd time and date: " + s.getEndTimeDate() + "\n");
}
}
}
All help is appreciated, thank you.
When I see object created once like this:
User user = new User(null, null, null, null, null);
And then, no new User, I understand that you never create new instance of your object.
The rest of the code is in the same vein: you are (almost) creating only one instance of an object, rather than a new instance.
Therefore, when you change a property of said instance, it affect all objects.
You need to add somewhere in your code, when you feel that with the data entered by the user (and read by the Scanner), you may create a new User, Stream, ...
For example, after this:
list.addJoinableList(stream);
Do:
stream = new Stream(....);

Writing and Reading to/from a file Objects stored in ArrayList

This is a simple example where I'm trying to write and read Objects stored in ArrayList to/from file.
Writing file is working. Reading file is working only for first Object in my ArrayList. How should I make this into a loop?
I tried with something like:
`while(ois !=null) {
Person result = (Person) ois.readObject();
persons.add(result);
}
but it's not working.
Here is full test code:
public class Data {
static ArrayList<Person> persons = new ArrayList<Person>();
public static void savePersons() throws IOException{
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object for examle */
for(int i = 0; i<5; i++){
Person personTest = new Person("name", "surname", "email", "1234567890");
persons.add(personTest);
}
try{
fout = new FileOutputStream("C:\\data.dat", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
System.out.println("Saving '" +persons.size()+ "' Object to Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR");
} finally {
if(oos != null){
oos.close();
}
}
}
public static void loadPersons() throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
/** Clean 'persons' array for TEST of load data*/
persons.removeAll(persons);
try {
fis = new FileInputStream("C:\\data.dat");
ois = new ObjectInputStream(fis);
Person result = (Person) ois.readObject();
persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" +persons.size()+ "' Object from Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("loadPersons() = OK");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR");
} finally {
if(ois != null){
ois .close();
}
}
}
}
Person class:
public class Person implements Serializable {
private String name;
private String surname;
private String mail;
private String telephone;
Person person;
public Person(String n, String s, String m, String t){
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}}
Main class:
public class Test {
public static void main(String[] args) {
Data.savePersons();
Data.loadPersons();
}}
Here you go... please take note of the following:
YES, Chetan Jadhav CD's suggestion WORKS. B
Use an IDE like Eclipse to help you debug your code and make your life easier.
Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:
System.out.println("Saving ERROR: " + ex.getMessage());
Put all your code in one file before you ask for help to make everyone's life easier.
Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Data {
private static final String SER_FILE = "C:\\view\\data.ser";
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons();
Data.loadPersons();
}
public static void savePersons() throws IOException {
/** Make 5 'Person' object for example */
for (int i = 0; i < 5; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
persons.add(personTest);
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
}
}
public static void loadPersons() throws IOException {
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
persons.stream().forEach(System.out::println);
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
}
}
}
class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}
#Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
}
}

File Reader Format

This project I'm working on, here is the function which write data's in to file :
public void writetofile(){
String bucky[]={custname,custlname,agee,address,id};
for(int i = 0; i < bucky.length; i++) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("records.txt", true))) {
String s;
s = bucky[i];
bw.write(s);
bw.newLine();
bw.flush();
}
catch(IOException ex) {
JOptionPane.showMessageDialog(null, "Error In File");
}
}
};
and there is another function defined which reads data's from file ,
public void filereader (){
int i=0;
Object[] options = {"OK"};
try
{
FileInputStream in = new FileInputStream("records.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
StringBuffer sb = new StringBuffer();
while((strLine = br.readLine())!= null)
{
sb.append(strLine +"\n");
}
JOptionPane.showMessageDialog( null, sb.toString());
}catch(Exception e){
JOptionPane.showOptionDialog(null, "Error", "Customers", JOptionPane.PLAIN_MESSAGE,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
}
};
and the problem is , let's say I want to create an account for a customer in my project , so few questions were asked such as name , last name , gender , etc. and all those info's have been saved , but when I try to read files all the data's will appear in no format , I want them to be appear in the proper way like this :
customer name : Michelle ,
gender : Female ;
but right now it appears as this :
michelle ,
female ,
You can construct the desired output first and callbw.write(s); only once
or follow R.J 's suggestion. Put everything to an object and override toString methid of that class. This will be the perfect way of solving your problem
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Customer
{
private final String firstName;
private final String lastName;
private final String address;
private final int age;
private final int id;
public Customer(String firstName, String lastName, String address, int age,
int id)
{
super();
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.age = age;
this.id = id;
}
#Override
public String toString ()
{
return "Customer [firstName=" + firstName + ", lastName=" + lastName
+ ", address=" + address + ", age=" + age + "]";
}
public static void main (String[] args)
{
}
public void writetofile (String custname, String custlname, int agee,
String address, int age)
{
Customer customer = new Customer(custname, custlname, address, age, id);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(
"records.txt", true)))
{
String s = customer.toString();
bw.write(s);
bw.newLine();
bw.flush();
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Error In File");
}
}
}

Trouble with a small library-management program

I'm having major trouble piecing this together. I have basic read and write functionality. What I need is for the input from file 'Books.txt' to be checked so that:
ISBN is valid
CopyNumber, Year and Statistics should be numeric
Title, Author and Publisher must contain values
BorrowDate must be a valid date
ReturnDate if available must be a valid date
LibraryCardNumber if available must be numeric.
If a book is not borrowed the two last fields are nonexistent.
2 sample rows from 'Books.txt':
9780140455168#2#The Twelve Caesars#Suetonius#Penguin Classics#2007#3#101009#101030#5478
9780141188607#1#Claudius the God#Robert Graves#Penguin Classics#2006#2#080123
Error lines should be written to 'ErrorLines.txt' with an error-message, e.g. Wrong ISBN. Error-free books should be written to 'NewBooks.txt' sorted by name of author.
Here's what I've got so far. I'm not looking for a complete solution, because I obviously have a looong way to go, but if someone would be so kind as to give me some pointers, I'd be extremely grateful! And yes, it's homework :D
Do I need to make a try loop to validate the input...?
The Library class:
import java.util.ArrayList;
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Library {
public void readFromFile (String filename) throws IOException {
String inLine;
File inFile;
inFile = new File("Books.txt");
BufferedReader fIn = new BufferedReader(new FileReader(inFile));
inLine = fIn.readLine();
while (inLine != null) {
inLine = fIn.readLine();
aBookList.add(inLine + "\n");
}
fIn.close();
}
public void writeToFile (String fileName) throws IOException {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(fileName));
bw.write("???"); //Dont know what to put here...
bw.newLine();
} catch (IOException e) {
System.out.println("Error writing file.");
} finally {
bw.close();
}
}
public static boolean isISBN13Valid(isbn) {
int check = 0;
for (int i = 0; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1));
}
for (int i = 1; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1)) * 3;
}
check += Integer.valueOf(isbn.substring(12));
return check % 10 == 0;
}
}
And here's the Book class:
import java.util.*;
import java.io.*;
public class Book {
Book b = new Book();
private static ArrayList<String> aBookList = new ArrayList<String>();
private String Isbn;
private int CopyNumber;
private String Title;
private String Author;
private String Publisher;
private int Year;
private int Statistics;
private String BorrowDate;
private String ReturnDate;
private int LibraryCardNumber;
public void bookInfo (String nIsbn, int nCopyNumber, String nTitle, String nAuthor, String nPublisher, int nYear,
int nStatistics, String nBorrowDate, String nReturnDate, int nLibraryCardNumber) {
Isbn = nIsbn;
CopyNumber = nCopyNumber;
Title = nTitle;
Author = nAuthor;
Publisher = nPublisher;
Year = nYear;
Statistics = nStatistics;
BorrowDate = nBorrowDate;
ReturnDate = nReturnDate;
LibraryCardNumber = nLibraryCardNumber;
}
public void bookInfo (String Row) {
StringTokenizer sT = new StringTokenizer(Row);
Isbn = sT.nextToken("#");
CopyNumber = Integer.parseInt(sT.nextToken("#") );
Title = sT.nextToken("#");
Author = sT.nextToken("#");
Publisher = sT.nextToken("#");
Year = Integer.parseInt(sT.nextToken("#") );
Statistics = Integer.parseInt(sT.nextToken("#") );
BorrowDate = sT.nextToken("#");
ReturnDate = sT.nextToken("#");
LibraryCardNumber = Integer.parseInt(sT.nextToken("#") );
}
public void setIsbn(String nIsbn) {
Isbn = nIsbn;
}
public void setCopynumber(int nCopyNumber) {
CopyNumber = nCopyNumber;
}
public void setTitle(String nTitle) {
Title = nTitle;
}
public void setAuthor(String nAuthor) {
Author = nAuthor;
}
public void setPublisher(String nPublisher) {
Publisher = nPublisher;
}
public void setYear(int nYear) {
Year = nYear;
}
public void setStatistics(int nStatistics) {
Statistics = nStatistics;
}
public void setBorrowDate(String nBorrowDate) {
BorrowDate = nBorrowDate;
}
public void setReturnDate(String nReturnDate) {
ReturnDate = nReturnDate;
}
public void setLibraryCardNumber(int nLibraryCardNumber) {
LibraryCardNumber = nLibraryCardNumber;
}
public String getAll () {
String s = " ";
return (Isbn + s + CopyNumber + s + Title + s + Author + s + Publisher + s +
Year + s + Statistics + s + BorrowDate + s + ReturnDate + s +
LibraryCardNumber);
}
public void showAll () {
String t = "\t";
System.out.println(Isbn + t + CopyNumber + t + Title + t + Author + t +
Publisher + t + Year + t + Statistics + t +
BorrowDate + t + ReturnDate + t + LibraryCardNumber);
}
}
And finally there's the Main class with main method:
public class Main<aBookList> implements Comparable<aBookList> {
public static void main(String [] args) throws Exception {
new Library().readFromFile("Books.txt");
new Library().writeToFile("NewBooks.txt");
new Library().writeToFile("ErrorLines.txt");
}
#Override
public int compareTo(aBookList o) {
return 0;
}
}
as it is homework, i will point you direction, not give you code
1) you have lot of mess here, ie i'm not sure why you have compare in your main class? instead of creating getAll method in bookInfo(which is named against java nameing convention) just override toString method
2) why do you have list of strings? read a line, convert this into book, if book is valid add it to your list, otherwise report an error
3) move your isISBN13Valid method to book
4) write to file -> loop through your list, and save each element into file by bw.write(book.toString()),
5) create second method createErrorFile, then each error what you will have add into your error list, and after you call that method, you will sace each element into given file, it is not perfetc solution, better will be if you add error to file each time when it occur.
6) create one instance of library in your main method, and just call on it all your method, and avoid using static fields in your project(sometimes you must, but if you don;t need, just avoid them)
7) names for method import/ export i think sounds nicer than read from file read from file

Categories

Resources