I have Person class and its properties are:
public class Person {
String Name;
Gender gender;
Person father;
Person mother;
Person partner;
ArrayList<Person> childs = new ArrayList<Person>();
public enum Gender {
MAN, WOMAN
}
public Person(String name, Gender gender){
this.Name = name;
this.gender = gender;
}
public void marryTo(Person person){
this.partner = person;
person.partner = this;
}
public void setChildFromMarriage(Person child){
childs.add(child);
partner.childs.add(child);
}
}
I am getting the properties of persons from a txt file. Each line represents one person. Properties in a line are separated by a slash.
Txt file: https://i.stack.imgur.com/ha3Wi.png
package classPackage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import classPackage.Person.Gender;
public class MainClass {
public static void main (String[] args)
{
try {
MainClass obj = new MainClass ();
obj.run ();
} catch (Exception e) {
e.printStackTrace ();
}
}
ArrayList<Person> persons = new ArrayList<Person>();
public void run () {
ArrayList<String> lines = null;
try {
lines = readFile("/persons.txt");
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(String line: lines) {
Person p = loadPerson(line);
persons.add(p);
}
}
private Person loadPerson(String line) {
StringBuilder sb = new StringBuilder();
int which_gender = 0;
Gender gender = null;
String name = null;
int which_father = 0;
int which_mother = 0;
int which_partner = 0;
int s = 0;
String strS;
for (int j = 0; j < line.length(); j++) {
char ch = line.charAt(j);
if ((int) ch == 47) {
strS = sb.toString();
s++;
sb.setLength(0);
if (s == 1) {
which_gender = Integer.parseInt(strS);
if(which_gender == 0) {
gender = Gender.MAN;
} else if(which_gender == 0) {
gender = Gender.WOMAN;
}
}
else if(s == 2)
name = strS;
else if(s == 3)
which_father = Integer.parseInt(strS);
else if(s == 4)
which_mother = Integer.parseInt(strS);
else if(s == 5)
which_partner = Integer.parseInt(strS);
} else {
sb.append(ch);
}
}
Person person = new Person(name, gender);
if(which_father != -1) {
person.father = persons.get(which_father);
}
if(which_mother != -1) {
person.mother = persons.get(which_mother);
persons.get(which_mother).setChildFromMarriage(person);
}
if(which_partner != -1) {
person.marryTo(persons.get(which_partner));
}
return person;
}
private ArrayList<String> readFile(String filename) throws IOException, URISyntaxException {
File file = new File(getClass().getResource(filename).toURI());
BufferedReader reader = new BufferedReader(new FileReader(file));
ArrayList<String> lines = new ArrayList<String>();
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
break;
}
lines.add(line);
}
return lines;
}
}
I tried to summarize my problem with these lines of code.
My problem is:
I don't know if it is related to the primitiveness of the txt file but I have 2 problems.
e.g. I always need to initialize son objects after their father. Otherwise "persons.get(which_father);" It will return IndexOutOfBoundsException error.
For example, there are 10 people registered in my txt file. (0-9 index) Let the father of the person in 9.index be the person in index 3. When I delete the person in index 1 and delete and save the 1.index line from the txt file; now our man's father is in index 2, not index 3. Changing the number of the father from 3 to 2 is complicated.
I feel unnecessarily complicated to operate on the txt file. How can I solve these 2 problems and code complexity?
Related
I have a code that reads an id block of three lines from a text file, I want to split those lines in Strings and an int, and pass this to a constructor from another class.
Right now, this class asks for an id number and prints everything below the # sign, down to and including the third line of each id block. I want those three lines in each id to be parsed as 'name', 'age' and 'job' to an Employee class, in order to create an object of the id, like this: Employee("Richard Smith",22,"Electric engineer"). There will always be three lines in the file for an id, so how can I "find" those lines and split them into Strings and an int?
#1000
Richard Smith
22
Electric engineer
#1001
Elliot Smith
23
Physicist
public class RdB
{
String b; //file name
RdB(String ename) {
b = ename;
}
//info about an employee
boolean showE (String id) {
int ch;
String code, info;
//open the file with the info
try (BufferedReader showERdr =
new BufferedReader (new FileReader(b)))
{
do {
//read characters until a '#' is found
ch = showERdr.read();
//check
if(ch == '#') {
code = showERdr.readLine();
if(id.compareTo(code) == 0) { //found employee
do {
info = showERdr.readLine();
if(info != null) {
System.out.println(info);
}
} while(((info != null) &&
(info.compareTo("") != 0)));
return true;
}
}
} while(ch != -1);
}
catch(IOException exc) {
System.out.println("File error!");
return false;
}
return false; //employee not found
}
//Access a registered employee
String getE() {
String id = "";
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter id number: ");
try{
id = br.readLine();
}
catch(IOException exc) {
System.out.println("Access error");
}
return id;
}
}
Edit:
Employee class
class Employee {
private String name, job;
private int age;
public Employee (String name, int age, String job) {
this.name = name;
this.age = age;
this.job = job;
}
public String getName () {
return name;
}
public int getAge () {
return age;
}
public String getJob () {
return job;
}
}
You can simply use an ArrayList to save what you read from the file and process it later. Since you are certain about the features of your saved file that it will always contain 3 lines before the line which contains ID, here is the working code I wrote to solve your problem. You can see the output wrapped between ( )
Here is the code:
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class Emp{
public static void main(String[] args) throws IOException{
List data = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("PeopleData.txt"));
String str;
while((str = reader.readLine()) != null){
// System.out.println(str);
data.add(str);
}
for(int i= 0; i< data.size(); i ++){
i++;
System.out.println("(");
System.out.println(data.get(i));
String name = (String) data.get(i);
i++;
System.out.println(data.get(i));
int age = Integer.valueOf((String) data.get(i));
i++;
System.out.println(data.get(i));
String job = (String) data.get(i);
i++;
System.out.println(")");
//new Employee(name, age, job);
}
}
}
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);
}
}
My program prints out a library. Each library is composed of books. Each book is composed of a title and the authors of that book. I have a driver program, a Library class, and a Book class. My issue is that when I use my driver program that uses my toString() methods in the library and book classes to print the library, the authors of each book are appearing as [author, ;, author, ;, author] and I want them to print as author; author; author.
Expected output: http://prntscr.com/810ik2
My output: http://prntscr.com/810ipp
My input: http://prntscr.com/810j6f
getAuthors is the method in my driver program that separates the authors (In the input file that the authors are taken from authors are separated by '*' instead of separated by ';' which is what i need in my output)
Please let me know in the comments if there is too little info, too much info, if what I've given is too confusing, or if I didn't explain anything properly. I'm new to Java and fairly new at posting questions here so please go easy on me. Thank you!
Edit: Just in case here are my three classes (only the important stuff):
Book.java:
import java.util.*;
public class Book implements Comparable<Book>
{
private final String myTitle;
private final ArrayList<String> myAuthors;
public Book(final String theTitle, final ArrayList<String> theAuthors)
{
if (theTitle == "" || theAuthors.isEmpty() ||
theTitle == null || theAuthors.get(0) == null)
{
throw new IllegalArgumentException(
"The book must have a valid title AND author.");
}
else
{
myTitle = theTitle;
myAuthors = new ArrayList<String>();
for (int i = 0; i < theAuthors.size(); i++)
{
myAuthors.add(theAuthors.get(i));
}
}
}
public String toString()
{
String result = "\"" + myTitle + "\" by ";
for (int i = 0; i < myAuthors.size(); i++)
{
result += (String)myAuthors.get(i);
}
return result;
}
}
Library.java:
import java.util.*;
public class Library
{
public Library(final ArrayList<Book> theOther)
{
if (theOther == null)
{
throw new NullPointerException();
}
else
{
myBooks = new ArrayList<Book>();
for (int i = 0; i < theOther.size(); i++)
{
myBooks.add(theOther.get(i));
}
}
}
public ArrayList<Book> findTitles(final String theTitle)
{
ArrayList<Book> titleList = new ArrayList<Book>();
for (int i = 0; i < myBooks.size(); i++)
{
if (myBooks.get(i).getTitle().equals(theTitle))
{
titleList.add(myBooks.get(i));
}
}
return titleList;
}
public String toString()
{
String result = "";
for (int i = 0; i < myBooks.size(); i++)
{
String tempTitle = myBooks.get(i).getTitle();
ArrayList<String> tempAuthors = myBooks.get(i).getAuthors();
Book tempBook = new Book(tempTitle, tempAuthors);
result += (tempBook + "\n");
}
return result;
}
}
LibraryDriver.java:
import java.util.*;
import java.io.*;
public class LibraryDriver
{
public static void main(String[] theArgs)
{
Scanner inputFile = null;
PrintStream outputFile = null;
ArrayList<String> authors = new ArrayList<String>();
ArrayList<Book> books = new ArrayList<Book>();
ArrayList<Book> books2 = new ArrayList<Book>();
String[] filesInputs = new String[]{"LibraryIn1.txt", "LibraryIn2.txt"};
try
{
outputFile = new PrintStream(new File("LibraryOut.txt"));
for (String fileInput : filesInputs)
{
inputFile = new Scanner(new File(fileInput));
while (inputFile.hasNext())
{
String title = "";
String input = inputFile.nextLine();
//Read title
title = input;
input = inputFile.nextLine();
authors = getAuthors(input);
//Insert title & authors into a book
Book tempBook = new Book(title, authors);
//Add this book to the ArrayList<Book> of books
books.add(tempBook);
}
Library myLib = new Library(books);
outputFile.println(myLib);
inputFile.close();
myLib.sort();
outputFile.println(myLib);
}
}
catch (Exception e)
{
System.out.println("Difficulties opening the file! " + e);
System.exit(1);
}
inputFile.close();
outputFile.close();
}
public static ArrayList<String> getAuthors(String theAuthors)
{
int lastAsteriskIndex = 0;
ArrayList<String> authorList = new ArrayList<String>();
for (int i = 0; i < theAuthors.length(); i++)
{
if (theAuthors.charAt(i) == '*')
{
if (lastAsteriskIndex > 0)
{
authorList.add(";");
authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
}
else
{
authorList.add(theAuthors.substring(0, i));
}
lastAsteriskIndex = i;
}
}
if (lastAsteriskIndex == 0)
{
authorList.add(theAuthors);
}
return authorList;
}
}
So, I hobbled together a runnable example of your code as best as I could and using
The Hobbit
Tolkien, J.R.R
Acer Dumpling
Doofus, Robert
As input, I get
"The Hobbit" by Tolkien, J.R.R
"Acer Dumpling" by Doofus, Robert
The code:
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class LibraryDriver {
public static void main(String[] theArgs) {
// ArrayList<Book> books = new ArrayList<>(25);
// books.add(
// new Book("Bananas in pajamas",
// new ArrayList<>(Arrays.asList(new String[]{"B1", "B2"}))));
//
// Library lib = new Library(books);
// System.out.println(lib.toString());
Scanner inputFile = null;
PrintStream outputFile = null;
ArrayList<String> authors = new ArrayList<String>();
ArrayList<Book> books = new ArrayList<Book>();
ArrayList<Book> books2 = new ArrayList<Book>();
String[] filesInputs = new String[]{"LibraryIn1.txt"}; //, "LibraryIn2.txt"};
try {
outputFile = new PrintStream(new File("LibraryOut.txt"));
for (String fileInput : filesInputs) {
inputFile = new Scanner(new File(fileInput));
while (inputFile.hasNext()) {
String title = "";
String input = inputFile.nextLine();
//Read title
title = input;
input = inputFile.nextLine();
authors = getAuthors(input);
//Insert title & authors into a book
Book tempBook = new Book(title, authors);
//Add this book to the ArrayList<Book> of books
books.add(tempBook);
}
Library myLib = new Library(books);
outputFile.println(myLib);
inputFile.close();
// myLib.sort();
// outputFile.println(myLib);
}
} catch (Exception e) {
System.out.println("Difficulties opening the file! " + e);
System.exit(1);
}
inputFile.close();
outputFile.close();
}
public static ArrayList<String> getAuthors(String theAuthors) {
int lastAsteriskIndex = 0;
ArrayList<String> authorList = new ArrayList<String>();
for (int i = 0; i < theAuthors.length(); i++) {
if (theAuthors.charAt(i) == '*') {
if (lastAsteriskIndex > 0) {
authorList.add(";");
authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
} else {
authorList.add(theAuthors.substring(0, i));
}
lastAsteriskIndex = i;
}
}
if (lastAsteriskIndex == 0) {
authorList.add(theAuthors);
}
return authorList;
}
public static class Library {
private ArrayList<Book> myBooks;
public Library(final ArrayList<Book> theOther) {
if (theOther == null) {
throw new NullPointerException();
} else {
myBooks = new ArrayList<Book>();
for (int i = 0; i < theOther.size(); i++) {
myBooks.add(theOther.get(i));
}
}
}
public ArrayList<Book> findTitles(final String theTitle) {
ArrayList<Book> titleList = new ArrayList<Book>();
for (int i = 0; i < myBooks.size(); i++) {
if (myBooks.get(i).getTitle().equals(theTitle)) {
titleList.add(myBooks.get(i));
}
}
return titleList;
}
public String toString() {
String result = "";
for (int i = 0; i < myBooks.size(); i++) {
String tempTitle = myBooks.get(i).getTitle();
Book b = myBooks.get(i);
ArrayList<String> tempAuthors = b.getAuthors();
Book tempBook = new Book(tempTitle, tempAuthors);
result += (tempBook + "\n");
}
return result;
}
}
public static class Book implements Comparable<Book> {
private final String myTitle;
private final ArrayList<String> myAuthors;
public Book(final String theTitle, final ArrayList<String> theAuthors) {
if (theTitle == "" || theAuthors.isEmpty()
|| theTitle == null || theAuthors.get(0) == null) {
throw new IllegalArgumentException(
"The book must have a valid title AND author.");
} else {
myTitle = theTitle;
myAuthors = new ArrayList<String>();
for (int i = 0; i < theAuthors.size(); i++) {
myAuthors.add(theAuthors.get(i));
}
}
}
public String toString() {
String result = "\"" + myTitle + "\" by ";
for (int i = 0; i < myAuthors.size(); i++) {
result += (String) myAuthors.get(i);
}
return result;
}
#Override
public int compareTo(Book o) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public String getTitle() {
return myTitle;
}
public ArrayList<String> getAuthors(String theAuthors) {
int lastAsteriskIndex = 0;
ArrayList<String> authorList = new ArrayList<String>();
for (int i = 0; i < theAuthors.length(); i++) {
if (theAuthors.charAt(i) == '*') {
if (lastAsteriskIndex > 0) {
authorList.add(";");
authorList.add(theAuthors.substring(lastAsteriskIndex + 1, i));
} else {
authorList.add(theAuthors.substring(0, i));
}
lastAsteriskIndex = i;
}
}
if (lastAsteriskIndex == 0) {
authorList.add(theAuthors);
}
return authorList;
}
public ArrayList<String> getAuthors() {
return myAuthors;
}
}
}
Consider providing a runnable example which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses
In this program iam able to read a file into an array and split the array. Then i have got an array method to sort the file by surname using bubble sort. However, i get an error. Can someone assist me please.
Error:
error: method BubbleCountry in class StudentSort cannot be applied to given types;
StudentSort.txt
Bren Ramal
Casi Ron
Alba Jordi
SortData file
import java.io.*;
import java.util.*;
class ShowSort implements Comparable {
private String name;
private String surname;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSurname() {
return surname;
}
public int compareTo(Object Student) throws ClassCastException {
if (!(Student instanceof ShowSort))
throw new ClassCastException("Error");
String surn = ((ShowSort) Student).getSurname();
return this.surname.compareTo(surn);
}
}
StudentSort file
import java.io.*;
import java.util.*;
public class StudentSort {
StudentSort() {
int j = 0;
ShowSort data[] = new ShowSort[3];
try {
FileInputStream fstream = new FileInputStream("StudentSort.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
ArrayList list = new ArrayList();
while ((line = br.readLine()) != null) {
list.add(line);
}
Iterator itr;
for (itr = list.iterator(); itr.hasNext();) {
String str = itr.next().toString();
String[] splitSt = str.split("\t");
String name = "", surname = "";
for (int i = 0; i < splitSt.length; i++) {
name = splitSt[0];
surname = splitSt[1];
}
BubbleCountry(surname);//This is the issue.
data[j] = new ShowSort();
data[j].setName(name);
data[j].setSurname(surname);
j++;
}
for (int i = 0; i < 3; i++) {
ShowSort show = data[i];
String name = show.getName();
String surname = show.getSurname();
System.out.println(name + "\t" + surname);
}
} catch (Exception e) {
}
}
private static void BubbleCountry(String[] myarray) {
String ctry;
for(int i=0; i<myarray.length; i++) {
for(int j=0; j<myarray.length-1-i; j++) {
if(myarray[j].compareTo(myarray[j+1])>0) {
ctry= myarray[j];
myarray[j] = myarray[j+1];
myarray[j+1] = ctry;
}
}
}
}
public static void main(String[] args) {
StudentSort data = new StudentSort();
}
}
You are calling BubbleCountry(surname); but its prototype shows
private static void BubbleCountry(String[] myarray)
So the difference is here. The function requires an array of string as argument but while calling you are passing a string rather than string array.
import java.io.*;
import java.util.*;
public class StudentSort
{
StudentSort()
{
int j = 0;
ShowSort data[] = new ShowSort[3];
try
{
FileInputStream fstream = new FileInputStream("StudentSort.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
list.add(line);
}
Iterator<String> itr = list.iterator();
int k = 0;
for (itr = list.iterator(); itr.hasNext();itr.next())
{
String str = itr.toString();
String[] splitSt = str.split("\t");
data[k].setName(splitSt[0]);
data[k].setName(splitSt[1]);
k++;
}
BubbleCountry(data);//This is the issue.
for (int i = 0; i < 3; i++)
{
ShowSort show = data[i];
String name1 = show.getName();
String surname1 = show.getSurname();
System.out.println(name1 + "\t" + surname1);
}
}
catch (Exception e)
{
}
}
private static void BubbleCountry(ShowSort[] myarray)
{
ShowSort ctry;
for(int i=0; i<myarray.length; i++)
{
for(int j=0; j<myarray.length-1-i; j++)
{
if(myarray[j].compareTo(myarray[j+1])>0)
{
ctry= myarray[j];
myarray[j] = myarray[j+1];
myarray[j+1] = ctry;
}
}
}
}
public static void main(String[] args)
{
StudentSort data = new StudentSort();
}
}
I work at a printing company that has many programs in COBOL and I have been tasked to
convert the COBOL programs into JAVA programs. I've run into a snag in the one conversion. I need to take a file that each line is a record and on each line the data is blocked.
Example of a line is
60000003448595072410013 FFFFFFFFFFV 80 0001438001000014530020120808060134
I need to sort data by a 5 digit number at the 19-23 characters and then by the very first character on a line.
BufferedReader input;
BufferedWriter output;
String[] sort, sorted, style, accountNumber, customerNumber;
String holder;
int lineCount;
int lineCounter() {
int result = 0;
boolean eof = false;
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
while (!eof) {
holder = input.readLine();
if (holder == null) {
eof = true;
} else {
result++;
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
return result;
}
chemSort(){
lineCount = this.lineCounter();
sort = new String[lineCount];
sorted = new String[lineCount];
style = new String[lineCount];
accountNumber = new String[lineCount];
customerNumber = new String[lineCount];
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
for (int i = 0; i < (lineCount + 1); i++) {
holder = input.readLine();
if (holder != null) {
sort[i] = holder;
style[i] = sort[i].substring(0, 1);
customerNumber[i] = sort[i].substring(252, 257);
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
}
This what I have so far and I'm not really sure where to go from here or even if this is the correct way
to go about sorting the file. After the file is sorted it will be stored into another file and processed
again with another program for it to be ready for printing.
List<String> linesAsList = new ArrayList<String>();
String line=null;
while(null!=(line=reader.readLine())) linesAsList.add(line);
Collections.sort(linesAsList, new Comparator<String>() {
public int compare(String o1,String o2){
return (o1.substring(18,23)+o1.substring(0,1)).compareTo(o2.substring(18,23)+o2.substring(0,1));
}});
for (String line:linesAsList) System.out.println(line); // or whatever output stream you want
This phone's autocorrect is messing up my answer
Read the file into an ArrayList (instead of an array). Use the following methods:
// to declare the arraylist
ArrayList<String> lines = new ArrayList<String>();
// to add a new line to it (within your reading-lines loop)
lines.add(input.readLine());
Then, sort it using a custom Comparator:
Collections.sort(lines, new Comparator<String>() {
public int compare(String a, String b) {
String a5 = theFiveNumbersOf(a);
String b5 = theFiveNumbersOf(b);
int firstComparison = a5.compareTo(b5);
if (firstComparison != 0) { return firstComparison; }
String a1 = theDigitOf(a);
String b1 = theDigitOf(b);
return a1.compareTo(b1);
}
});
(It is unclear what 5 digits or what digit you want to compare; I've left them as functions for you to fill in).
Finally, write it to the output file:
BufferedWriter ow = new BufferedWriter(new FileOutputStream("filename.extension"));
for (String line : lines) {
ow.println(line);
}
ow.close();
(adding imports and try/catch as needed)
This code will sort a file based on mainframe sort parameters.
You pass 3 parameters to the main method of the Sort class.
The input file path.
The output file path.
The sort parameters in mainframe sort format. In your case, this string would be 19,5,CH,A,1,1,CH,A
This first class, the SortParameter class, holds instances of the sort parameters. There's one instance for every group of 4 parameters in the sort parameters string. This class is a basic getter / setter class, except for the getDifference method. The getDifference method brings some of the sort comparator code into the SortParameter class to simplify the comparator code in the Sort class.
public class SortParameter {
protected int fieldStartByte;
protected int fieldLength;
protected String fieldType;
protected String sortDirection;
public SortParameter(int fieldStartByte, int fieldLength, String fieldType,
String sortDirection) {
this.fieldStartByte = fieldStartByte;
this.fieldLength = fieldLength;
this.fieldType = fieldType;
this.sortDirection = sortDirection;
}
public int getFieldStartPosition() {
return fieldStartByte - 1;
}
public int getFieldEndPosition() {
return getFieldStartPosition() + fieldLength;
}
public String getFieldType() {
return fieldType;
}
public String getSortDirection() {
return sortDirection;
}
public int getDifference(String a, String b) {
int difference = 0;
if (getFieldType().equals("CH")) {
String as = a.substring(getFieldStartPosition(),
getFieldEndPosition());
String bs = b.substring(getFieldStartPosition(),
getFieldEndPosition());
difference = as.compareTo(bs);
if (getSortDirection().equals("D")) {
difference = -difference;
}
}
return difference;
}
}
The Sort class contains the code to read the input file, sort the input file, and write the output file. This class could probably use some more error checking.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sort implements Runnable {
protected List<String> lines;
protected String inputFilePath;
protected String outputFilePath;
protected String sortParameters;
public Sort(String inputFilePath, String outputFilePath,
String sortParameters) {
this.inputFilePath = inputFilePath;
this.outputFilePath = outputFilePath;
this.sortParameters = sortParameters;
}
#Override
public void run() {
List<SortParameter> parameters = parseParameters(sortParameters);
lines = read(inputFilePath);
lines = sort(lines, parameters);
write(outputFilePath, lines);
}
protected List<SortParameter> parseParameters(String sortParameters) {
List<SortParameter> parameters = new ArrayList<SortParameter>();
String[] field = sortParameters.split(",");
for (int i = 0; i < field.length; i += 4) {
SortParameter parameter = new SortParameter(
Integer.parseInt(field[i]), Integer.parseInt(field[i + 1]),
field[i + 2], field[i + 3]);
parameters.add(parameter);
}
return parameters;
}
protected List<String> sort(List<String> lines,
final List<SortParameter> parameters) {
Collections.sort(lines, new Comparator<String>() {
#Override
public int compare(String a, String b) {
for (SortParameter parameter : parameters) {
int difference = parameter.getDifference(a, b);
if (difference != 0) {
return difference;
}
}
return 0;
}
});
return lines;
}
protected List<String> read(String filePath) {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return lines;
}
protected void write(String filePath, List<String> lines) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(filePath));
for (String line : lines) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.err.println("The sort process requires 3 parameters.");
System.err.println(" 1. The input file path.");
System.err.println(" 2. The output file path.");
System.err.print (" 3. The sort parameters in mainframe ");
System.err.println("sort format. Example: 15,5,CH,A");
} else {
new Sort(args[0], args[1], args[2]).run();
}
}
}