I'm trying to figure out how to sort the arrayLists that come out of a .txt file. I want to be able to sort them alphabetically by name. Here is an example of how the txt file is listed:
Alvarez, Eliezer
74
2B
IA
22
Bowman, Matt
67
P
A
26
Each piece is on a single line by itself (except lastName, firstName being on a line together).
Is there a way to do a collections sort that will adjust the rest of the Arraylists based off the name Arraylist? Thanks.
Scanner keyboard = new Scanner(System.in);
String filename;
fileName = "cardinals.txt";
File baseball = new File(fileName);
if (!baseball.exists()) {
System.out.println("The input file was not found.");
System.exit(0);
}
ArrayList<String> name = new ArrayList<>();
ArrayList<Integer> number = new ArrayList<>();
ArrayList<String> position = new ArrayList<>();
ArrayList<String> status = new ArrayList<>();
ArrayList<Double> age = new ArrayList<>();
Scanner stats = new Scanner(baseball);
if (!stats.hasNext()) {
System.out.println("The file is empty.");
}
else {
while (stats.hasNext()) {
name.add(stats.nextLine());
number.add(stats.nextInt());
position.add(stats.next());
status.add(stats.next());
age.add(stats.nextDouble());
try {
stats.nextLine();
} catch (Exception e) {
}
}
} stats.close();
sortArrayPosition();
sortArrayPosition (ArrayList<String> name, ArrayList<Integer> number, ArrayList<String> position, ArrayList<String> status, ArrayList<Double> age) {
When organizing and managing complex data, using an object to group the data together is the best approach.
Here is an example using an object to store the information:
package example;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
class StatisticsReader {
private static class PlayerStats {
String name;
Integer number;
String position;
String status;
Double age;
public PlayerStats(String name, Integer number, String position, String status, Double age) {
this.name = name;
this.number = number;
this.position = position;
this.status = status;
this.age = age;
}
#Override
public String toString() {
return "PlayerStats{" +
"name='" + name + '\'' +
", number=" + number +
", position='" + position + '\'' +
", status='" + status + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) {
File baseball = new File("cardinals.txt");
if (!baseball.exists()) {
System.out.println("The input file was not found.");
System.exit(0);
}
List<PlayerStats> statsList = new ArrayList<>();
try (Scanner stats = new Scanner(baseball)) {
if (!stats.hasNext()) {
System.out.println("The file is empty.");
}
else {
while (stats.hasNext()) {
String name = stats.nextLine();
Integer number = stats.nextInt();
String position = stats.next();
String status = stats.next();
Double age = stats.nextDouble();
statsList.add(new PlayerStats(name, number, position, status, age));
stats.nextLine();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
statsList.sort(Comparator.comparing(o -> o.name));
statsList.forEach(System.out::println);
}
}
You can customize the toString() method to change the output if necessary.
Related
I have a class that takes in a txt file with artists and their genre in the format:
Abba Rock
Beethoven Classical
I am trying to write a method "public int count(String genre)" that counts the amount of times that word/genre is present. For example, for rock, it would need to count the number of rock artists and satisfy my test case:
public class ArtistTest
{
public static void main(String[] args)
{
Artists artists = new Artists();
System.out.println(artists.count() + " artists in the list");
System.out.println(artists.count("Rock") + " rock artists in the list\n");
My initial count method successfully counts the number of artists (I guess there would be a better way to do that)
My code so far:
import java.io.File;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Scanner;
public class Artists {
public static ArrayList<String> artists = new ArrayList<String>();
public static void main(String[] args) {
System.out.println(readArtists("artists30.txt"));
System.out.println(artists + "\n");
}
public Artists() {
}
public static boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("err " + fileName);
return false;
}
sc = new Scanner(file);
while (sc.hasNextLine()) {
artists.add(sc.nextLine());
}
} catch (Exception e) {
e.printStackTrace();
}
if (sc != null) {
sc.close();
}
return true;
}
public int count() {
int count = artists.size();
return count;
}
public int count(String genre) {
}
}
What I'm testing with:
public class ArtistTest
{
public static void main(String[] args)
{
Artists artists = new Artists();
System.out.println(artists.count() + " artists in the list");
System.out.println(artists.count("Rock") + " rock artists in the list\n");
System.out.println("File opened successfully? " + artists.readArtists("artists30.txt"));
System.out.println("\n" + artists.count() + " artists in the list");
System.out.println(artists.count("Rock") + " rock artists in the list");
System.out.println(artists.count("R&B") + " R&B artists in the list");
}
}
I'm old school. All that new Streams stuff spins my head around. I like to keep things simple. My way to what you want is to do two simple things:
Define an Artist object that will represent the info on each artist. This object knows how to construct itself from a line in the data file.
While reading in the artists, create a second by-genre index that will give you a list of artists for each genre.
The other thing I did was make things non-static, so you actually instantiate an Artists object, in case you ever wanted to have multiple lists of artists.
Here's my rendition:
import java.util.*;
import java.io.File;
import java.util.Scanner;
public class Artists {
public class Artist {
public String name;
public String genre;
public Artist(String line) {
String[] parts = line.trim().split("\\s+");
name = parts[0];
genre = parts[1];
}
}
private List<Artist> artists = new ArrayList<>();
private Map<String, List<Artist>> genres = new HashMap<>();
public boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("err " + fileName);
return false;
}
sc = new Scanner(file);
while (sc.hasNextLine()) {
// Turn the line into an Artist object
Artist artist = new Artist(sc.nextLine());
// Add it to the main list of artists
artists.add(artist);
// Add it to the per-genre index
if (!genres.containsKey(artist.genre))
genres.put(artist.genre, new ArrayList<>());
genres.get(artist.genre).add(artist);
}
} catch (Exception e) {
e.printStackTrace();
}
if (sc != null) {
sc.close();
}
return true;
}
public int count() {
return artists.size();
}
public int count(String genre) {
if (genres.containsKey(genre))
return genres.get(genre).size();
return 0;
}
public static void main(String[] args) {
Artists artists = new Artists();
String filepath = "/tmp/artists30.txt";
if (artists.readArtists(filepath)) {
System.out.printf("Artist Count: %d\n", artists.count());
System.out.printf("Rock Artist Count: %d\n", artists.count("Rock"));
}
else {
System.out.printf("Failed to read artists file '%s'\n", filepath);
}
}
}
Sample Data:
Abba Pop
Beethoven Classical
Rush Rock
Aerosmith Rock
Mozart Classical
AC/DC Rock
Yes Rock
Result:
Artist Count: 7
Rock Artist Count: 4
Well as long as your mapping will be "artist" + "space" + "genre" you could try the following code. This creates a map with all the genres as key, and the value is the respective count for the genre.
class Grouper {
public static void main(String[] args) {
var grouper = new Grouper();
grouper.groupByGenre();
}
void groupByGenre() {
List<String> musicCollection = List.of("Kid Rock", "Hello Rock", "Beethoven Classical");
var collection = musicCollection.stream()
.map(entry -> entry.split(" "))
.filter(strings -> strings.length == 2)
.map(strings -> new MusicCollection(strings[0], strings[1]))
.collect(Collectors.groupingBy(MusicCollection::getGenre, Collectors.counting()));
System.out.println(collection);
}
}
class MusicCollection {
private final String artist;
private final String genre;
public MusicCollection(String artist, String genre) {
this.artist = artist;
this.genre = genre;
}
public String getArtist() {
return artist;
}
public String getGenre() {
return genre;
}
}
EDIT:
To make it simpeler, replace your count method with the following:
public int count(String genre)
{
return (int) artists.stream()
.map(entry -> entry.split(" "))
.filter(strings -> strings.length == 2)
.map(strings -> strings[1])
.filter(value -> Objects.equals(value, genre))
.count();
}
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(....);
I am trying to read from a text file of the type (Artist, Title, Genre, Recordcompany, Release year, Number of songs, Playtime):
The Beatles, Abbey Road, Rock, Apple Records, 1969, 17, 47.16
Sia, 1000 Forms of Fear, Pop, Intertia, 2014, 12, 48.41
Taylor Swift, Speak Now
I have created a CD class:
package q;
public class CD {
//
private String artist;
private String titel;
private String genre;
private String recordcompany;
private int year; //
private int songs; //
private double playtime; //
public CD() { //
}
public CD(String newArtist, String newTitel) {
artist = newArtist;
titel = newTitel;
}
public CD(String newArtist, String newTitel, String newGenre, String newRecordcompany, int newYear, int newSongs, double newPlaytime) {
artist = newArtist;
titel = newTitel;
genre = newGenre;
recordcompany = newRecordcompany;
year = newYear;
songs = newSongs;
playtime = newPlaytime;
}
public String getArtist() { //
return artist;
}
public String getTitel() {
return titel;
}
public String getGenre() {
return genre;
}
public String getRecordcompany() {
return recordcompany;
}
public int getYear() {
return year;
}
public int getsong() {
return songs;
}
public double getPlaytime() {
return playtime;
}
public void setArtist(String newArtist) { //
artist = newArtist;
}
public void setTitel(String newTitel) {
titel = newTitel;
}
public void setGenre(String newGenre) {
genre = newGenre;
}
public void setRecordcompany(String newRecordcompany) {
recordcompany = newRecordcompany;
}
public void setYear(int newYear) {
year = newYear;
}
public void setSongs(int newSongs) {
songs = newSongs;
}
public void setplaytime(double newPlaytime) {
playtime = newPlaytime;
}
#
Override public String toString() { //
return ("Artist " + artist + System.lineSeparator() + "Titel: " + titel + System.lineSeparator() + "Genre: " + genre + System.lineSeparator() + "Recordcompany: " + recordcompany + System.lineSeparator() + "Year: " + year + System.lineSeparator() + "Songs: " + songs + System.lineSeparator() + "Playtime: " + playtime + System.lineSeparator());
}
}
I am trying to read from the text file and then convert it into a arraylist. I know I have overcomplicated it by first conerting the text file to a string array and then converting it to an arraylist. I would like to use set and get methods when I create the array, if it is possible. I wonder if any of you have any tips for me for how I can make the code less complicated and include set and get methods if possible, thank you.
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
String year = "";
String songs = "";
String playtime = "";
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String tmp[] = line.split(",");
artist = tmp[0];
titel = tmp[1];
if (tmp.length > 2) {
genre = tmp[2];
recordcompany = tmp[3];
year = (tmp[4]);
songs = (tmp[5]);
playtime = (tmp[6]);
} else {
genre = "";
recordcompany = "";
year = "";
songs = "";
playtime = "";
}
List < String > unsorted = Arrays.asList(tmp);
for (String e: unsorted) {
System.out.println(e);
}
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
EDITED
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
int year = 0;
int songs = 0;
double playtime = 0.0;
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
System.out.println(cdsList);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Something like below.
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
cdsList.add(cd);
}
System.out.println(cdsList);
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
I have a text file that looks like this.
BEGINNING OF LIST
Name: Janet
Age: 21
Birthday month: April
END OF LIST
BEGINNING OF LIST
Name: Peter
Age: 34
Birthday month: January
END OF LIST
So I want to grab info and put it into an object array. it is an extensive list and I am using the delimiters beginning of list and end of list to delimit the content.
How can I store these items in an object array?
I would suggest you create a class first for storing the information, with name, age, and birthday month attributes. It's a very good practice to override the toString() method so you can print out the class neatly.
Then you can check for each line whether it contains information about the name, age, or birthday month through splitting each line into an array of words, and checking for the information.
Once the line reads "END OF LIST", you can add a class Person with the parameters to the ArrayList.
For the example I used "people.txt" as the file (make sure you place the text document outside of the src folder which contains your .java files).
Main.java
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args)
{
BufferedReader bufferedReader = null;
FileReader fileReader = null;
String name = null;
String age = null;
String month = null;
List<Person> people = new ArrayList<Person>();
try
{
String fileName = "people.txt";
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
String[] information = line.split(" ");
if (Arrays.asList(information).contains("Name:"))
{
name = information[1];
}
if (Arrays.asList(information).contains("Age:"))
{
age = information[1];
}
if (Arrays.asList(information).contains("month:"))
{
month = information[2];
}
if (line.equals("END OF LIST"))
{
people.add(new Person(name, age, month));
name = "";
age = "";
month = "";
}
}
for (Person person : people)
{
System.out.println(person);
System.out.print("\n");
}
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
catch (IOException ex)
{
System.out.println("Error reading people.txt");
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
if (fileReader != null)
{
try
{
fileReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
}
}
Person.java
public class Person {
private String name;
private String age;
private String birthday;
public Person(String name, String age, String birthday)
{
this.name = name;
this.age = age;
this.birthday = birthday;
}
#Override
public String toString()
{
String information = "Name: " + name + "\nAge: " + age + "\nBirthday: " + birthday;
return information;
}
}
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