Using Bubble sort to sort file by surname? - java

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();
}
}

Related

How to write a LinkedList to a .txt file

Super simple program. Loop asking for student data (name, address, gpa) which is stored in a linked list. Output the data to a regular text file that can be opened in notepad.
I'm so close, but cannot figure out how to get my data written into the txt file. To start, here's my classes:
public class Student {
private String name;
private String address;
private double gpa;
public Student(String name, String address, double gpa) {
this.name = name;
this.address = address;
this.gpa = gpa;
}
public String getName() {
return this.name;
}
public String getAddress() {
return this.address;
}
public double getGpa() {
return this.gpa;
}
public String toString() {
return this.name + ", " + this.address + ", " + this.gpa;
}
public class WriteFile {
private String path;
private boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textLine)throws IOException {
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 3;
String[] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
In main I can get it to write the "Text to be written to file" into my .txt file, but I still can't figure out how to write studentData into that file.
public class Main {
public static void main(String[] args) throws IOException {
LinkedList < Student > studentData = new LinkedList < > ();
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.lineSeparator());
while (true) {
System.out.println("Student name: ");
String name = scanner.next();
if (name.isEmpty()) {
break;
}
System.out.println("Student address: ");
String address = scanner.next();
System.out.println("Student GPA: ");
double gpa = scanner.nextDouble();
studentData.add(new Student(name, address, gpa));
}
studentData.sort(Comparator.comparing(Student::getName));
for (Student info: studentData) {
System.out.println(info.getName() + "," + info.getAddress() + "," + info.getGpa());
}
String file_name = "C:\\Users\\hidden\\OneDrive - hidden\\Desktop\\Portfolio_Project.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++) {
System.out.println(aryLines[1]);
}
} catch (IOException e) {
System.out.println("Error. Please try again.");
}
// Write to a file
WriteFile data = new WriteFile(file_name);
data.writeToFile("Text to be written to file");
System.out.println("Text File Written To Portfolio_Project.txt on Desktop");
}
}

How do I get rid of complexity in txt file?

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?

Reading textfile with multiple elements into arraylist (set and get)

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);
}
}

Java - printing all ArrayList elements as a single String

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

error cannot find symbol and class discrete Attribute

import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class FileReader
{
public static final String PATH_TO_DATA_FILE = "playtennis.data";
public static ArrayList<Record> buildRecords() {
BufferedReader reader = null;
DataInputStream dis = null;
ArrayList<Record> records = new ArrayList<Record>();
try {
File f = new File(PATH_TO_DATA_FILE);
FileInputStream fis = new FileInputStream(f);
reader = new BufferedReader(new InputStreamReader(fis));;
// read the first record of the file
String line;
Record r = null;
ArrayLAist<DiscreteAttribute> attributes;
while ((line = reader.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ",");
attributes = new ArrayList<DiscreteAttribute>();
r = new Record();
if(Hw1.NUM_ATTRS != st.countTokens()) {
throw new Exception("Unknown number of attributes!");
}
#SuppressWarnings("unused")
String day = st.nextToken();
String outlook = st.nextToken();
String temperature = st.nextToken();
String humidity = st.nextToken();
String wind = st.nextToken();
String playTennis = st.nextToken();
if(outlook.equalsIgnoreCase("overcast")) {
attributes.add(new DiscreteAttribute("Outlook", DiscreteAttribute.Overcast));
}
else if(outlook.equalsIgnoreCase("sunny")) {
attributes.add(new DiscreteAttribute("Outlook", DiscreteAttribute.Sunny));
}
else if(outlook.equalsIgnoreCase("rain")) {
attributes.add(new DiscreteAttribute("Outlook", DiscreteAttribute.Rain));
}
if(temperature.equalsIgnoreCase("hot")) {
attributes.add(new DiscreteAttribute("Temperature", DiscreteAttribute.Hot));
}
else if(temperature.equalsIgnoreCase("mild")) {
attributes.add(new DiscreteAttribute("Temperature", DiscreteAttribute.Mild));
}
else if(temperature.equalsIgnoreCase("cool")) {
attributes.add(new DiscreteAttribute("Temperature", DiscreteAttribute.Cool));
}
if(humidity.equalsIgnoreCase("high")) {
attributes.add(new DiscreteAttribute("Humidity", DiscreteAttribute.High));
}
else if(humidity.equalsIgnoreCase("normal")) {
attributes.add(new DiscreteAttribute("Humidity", DiscreteAttribute.Normal));
}
if(wind.equalsIgnoreCase("weak")) {
attributes.add(new DiscreteAttribute("Wind", DiscreteAttribute.Weak));
}
else if(wind.equalsIgnoreCase("strong")) {
attributes.add(new DiscreteAttribute("Wind", DiscreteAttribute.Strong));
}
if(playTennis.equalsIgnoreCase("no")) {
attributes.add(new DiscreteAttribute("PlayTennis", DiscreteAttribute.PlayNo));
}
else if(playTennis.equalsIgnoreCase("yes")) {
attributes.add(new DiscreteAttribute("PlayTennis", DiscreteAttribute.PlayYes));
}
r.setAttributes(attributes);
records.add(r);
}
}
}
I haven given file name as FileReader
I'm getting errors on cannot file symbol
Cannot find symbol symbol:class discrete Attribute, location:class classifier.FileReader
Cannot find the symbol symbol:variable discrete Attribute location:class classifier.FileReader
Here DiscreteAttribute class. You need add that class your project.
public class DiscreteAttribute extends Attribute { public static final int Sunny = 0; public static final int Overcast = 1; public static final int Rain = 2; public static final int Hot = 0; public static final int Mild = 1; public static final int Cool = 2; public static final int High = 0; public static final int Normal = 1; public static final int Weak = 0; public static final int Strong = 1; public static final int PlayNo = 0; public static final int PlayYes = 1; enum PlayTennis { No, Yes } enum Wind { Weak, Strong } enum Humidity { High, Normal } enum Temp { Hot, Mild, Cool } enum Outlook { Sunny, Overcast, Rain } public DiscreteAttribute(String name, double value) { super(name, value); } public DiscreteAttribute(String name, String value) { super(name, value); } }

Categories

Resources