Library book sorting - java

I am in a java programming class and I cannot figure how to fix this error.
This is the error I keep getting:
Library.java:120: error: class, interface, or enum expected
import java.util.ArrayList;
^
1 error
This is the task
Two sorted lists have been created, one implemented using a linked list (LinkedListLibrary linkedListLibrary) and the other implemented using the built-in ArrayList class (ArrayListLibrary arrayListLibrary). Each list contains 100 books (title, ISBN number, author), sorted in ascending order by ISBN number.
Complete main() by inserting a new book into each list using the respective LinkedListLibrary and ArrayListLibrary insertSorted() methods and outputting the number of operations the computer must perform to insert the new book. Each insertSorted() returns the number of operations the computer performs.
Ex: If the input is:
The Catcher in the Rye
9787543321724
J.D. Salinger
the output is:
Number of linked list operations: 1
Number of ArrayList operations: 1
This is my code:
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
public class Library {
public static void fillLibraries(LinkedListLibrary linkedListLibrary, ArrayListLibrary arrayListLibrary) throws IOException {
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
int linkedListOperations = 0;
int arrayListOperations = 0;
BookNode currNode;
Book tempBook;
String bookTitle;
String bookAuthor;
long bookISBN;
// Try to open file
fileByteStream = new FileInputStream("Books.txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine()) {
bookTitle = inFS.nextLine();
bookISBN = inFS.nextLong();
inFS.nextLine();
bookAuthor = inFS.nextLine();
// Insert into linked list
currNode = new BookNode(bookTitle, bookAuthor, bookISBN);
linkedListOperations = linkedListLibrary.insertSorted(currNode, linkedListOperations);
linkedListLibrary.lastNode = currNode;
// Insert into ArrayList
tempBook = new Book(bookTitle, bookAuthor, bookISBN);
arrayListOperations = arrayListLibrary.insertSorted(tempBook, arrayListOperations);
}
fileByteStream.close(); // close() may throw IOException if fails
}
public static void main (String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int linkedListOperations = 0;
int arrayListOperations = 0;
// Create libraries
LinkedListLibrary linkedListLibrary = new LinkedListLibrary();
ArrayListLibrary arrayListLibrary = new ArrayListLibrary();
// Fill libraries with 100 books
fillLibraries(linkedListLibrary, arrayListLibrary);
// Create new book to insert into libraries
BookNode currNode;
Book tempBook;
String bookTitle;
String bookAuthor;
long bookISBN;
bookTitle = scnr.nextLine();
bookISBN = scnr.nextLong();
scnr.nextLine();
bookAuthor = scnr.nextLine();
// Insert into linked list
currNode = new BookNode(bookTitle, bookAuthor, bookISBN);
// TODO
int i = linkedListLibrary.insertSorted(currNode,0);
linkedListLibrary.lastNode = currNode;
// Insert into ArrayList
tempBook = new Book(bookTitle, bookAuthor, bookISBN);
// TODO
int j = arrayListLibrary.insertSorted(tempBook,0);
// TODO: Print number of operations for linked list
System.out.println("Number of operations for linked list : "+i);
// TODO: Print number of operations for ArrayList
System.out.println("Number of operations for ArrayList : "+j);
}
}
// Book.java
public class Book{
private String bookTitle;
private String bookAuthor;
private long bookISBN;
public Book() {
bookTitle = "";
bookAuthor = "";
bookISBN = 0;
}
public Book(String userBookTitle, String userBookAuthor, long userBookISBN) {
bookTitle = userBookTitle;
bookAuthor = userBookAuthor;
bookISBN = userBookISBN;
}
public long getBookISBN() {
return bookISBN;
}
public void printInfo(){
System.out.println("Title: " + bookTitle);
System.out.println("Author: " + bookAuthor);
System.out.println("ISBN: " + bookISBN);
}
}
// ArrayListLibrary.java
import java.util.ArrayList;
public class ArrayListLibrary {
// ArraryList library
public ArrayList<Book> library;
public ArrayListLibrary() {
library = new ArrayList<Book>();
}
public int insertSorted(Book newBook, int counter) {
Book currBook;
// Add an empty element at end of list
library.add(null);
// Loop through elements starting at the end
for (int i = library.size() - 2; i >=0; --i) {
currBook = library.get(i);
// If the current book's ISBN is larger than newBook's ISBN, shift
// the current book down 1, count shift operation
if(currBook.getBookISBN() > newBook.getBookISBN()){
library.set(i+1, currBook);
++counter;
}
// Otherwise, place newBook at the next location (empty slot),
// count insert operation
else {
library.set(i+1, newBook);
++counter;
return counter;
}
}
// If we get to the top of the list, place newBook on top
library.set(0, newBook);
++counter;
return counter;
}
public void printLibrary() {
for (int i = 0; i < library.size(); ++i) {
library.get(i).printInfo();
System.out.println();
}
}
}
// BookNode.java
public class BookNode {
private String bookTitle;
private String bookAuthor;
private long bookISBN;
private BookNode nextNodePtr; // Reference to the next node
public BookNode() {
bookTitle = "";
bookAuthor = "";
bookISBN = 0;
nextNodePtr = null;
}
// Constructor
public BookNode(String bookTitleInit, String bookAuthorInit, long bookISBNInit) {
this.bookTitle = bookTitleInit;
this.bookAuthor = bookAuthorInit;
this.bookISBN = bookISBNInit;
this.nextNodePtr = null;
}
// Constructor
public BookNode(String bookTitleInit, String bookAuthorInit, long bookISBNInit, BookNode nextLoc) {
this.bookTitle = bookTitleInit;
this.bookAuthor = bookAuthorInit;
this.bookISBN = bookISBNInit;
this.nextNodePtr = nextLoc;
}
// insertAfter
public void insertAfter(BookNode nodeLoc) {
BookNode tmpNext;
tmpNext = this.nextNodePtr;
this.nextNodePtr = nodeLoc;
nodeLoc.nextNodePtr = tmpNext;
}
//setNext
public void setNext(BookNode nodeLoc) {
this.nextNodePtr = nodeLoc;
}
// Get location pointed by nextNodePtr
public BookNode getNext() {
return this.nextNodePtr;
}
public long getBookISBN() {
return this.bookISBN;
}
// TODO: Print book information
public void printBookInfo() {
System.out.println("Title: " + this.bookTitle);
System.out.println("Author: " + this.bookAuthor);
System.out.println("ISBN: " + this.bookISBN);
}
}
// LinkedListLibrary.java
public class LinkedListLibrary {
//Linked list nodes
BookNode headNode;
BookNode lastNode;
LinkedListLibrary() {
// Front of nodes list
headNode = new BookNode();
lastNode = headNode;
}
public int insertSorted(BookNode newNode, int counter) {
BookNode currNode, nextNode;
// Special case for head node
if (headNode == null || headNode.getBookISBN() >= newNode.getBookISBN()) {
newNode.insertAfter(headNode);
headNode = newNode;
}
else {
// Locate the node before insertion point
currNode = headNode;
while (currNode.getNext() != null && currNode.getNext().getBookISBN() < newNode.getBookISBN()) {
currNode = currNode.getNext();
}
newNode.setNext(currNode.getNext());
currNode.insertAfter(newNode);
}
++counter;
return counter;
}
public void printLibrary() {
BookNode currNode;
currNode = headNode.getNext();
while (currNode != null) {
currNode.printBookInfo();
System.out.println();
currNode = currNode.getNext();
}
}
}

Did the same lab. They make it seem intimidating with the amount of files and text thrown at you, but to pass the lab you just need to add the two lines to the end of Library.java:
System.out.println("Number of linked list operations: " + linkedListLibrary.insertSorted(currNode, linkedListOperations));
System.out.println("Number of ArrayList operations: " + arrayListLibrary.insertSorted(tempBook, arrayListOperations));
To explain:
The lab was to help you go through established code and read its set methods to learn how to do work in a class you haven't made. If you followed the development stubs (#TODO's) you would trace the path to finding what you need to do. This is what leads to the solution in this case!

Related

Binary Search Tree (BST) search method for string

i've built a BST that have elements of (country code(string), indicator code(string), indicator name(string) and ArrayList of Years(int) and values(string)).
I'm trying to figure out how to prompt the user to search by entering Indicator code and then the year which the output will be the value.
it would be much appreciated if you could show how to code the search method cause I've tried everything.
I've tried this in the BST class. but it doesn't feel right(?)
public void search(Indicator indicator, String searchTerm){
String str = (String)indicator.getICode();
int n1 = str.compareTo(searchTerm);
int n2 = searchTerm.compareTo(str);
if (str == null || str.equalsIgnoreCase(searchTerm)){
return str;
}
if (n1 > n2){
return search(indicator, searchTerm);
}
else if (n1 < n2){
return search(indicator, searchTerm);
}
}
this is my application class:
public class BigDataBST{
public static void main (String [] Args) throws IOException {
try{
BST bigdata = new BST();
MyData d1;
File inFile = new File ("Indicator.txt");
FileReader fr = new FileReader (inFile);
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
while(str != null ){
StringTokenizer st = new StringTokenizer(str,";");
ArrayList <MyData> data = new ArrayList();
String cCode = st.nextToken();
String iName = st.nextToken();
String iCode = st.nextToken();
for (int j = 0; j < 59; j++){
String v = st.nextToken();
int year = 1960 + j;
d1 = new MyData (year,v);
data.add(d1);
}
Indicator idct = new Indicator (cCode,iName,iCode,data);
bigdata.insertNode(idct);
str = br.readLine();
}
TreeNode class:
TreeNode left;
TreeNode right;
Indicator idct;
public TreeNode(Indicator id){
left = right = null;
idct = id;
}
indicator class:
private String cCode; //country code
private String iName; //indicator Name;
private String iCode; //indicator code;
public ArrayList <MyData> DataList;
public Indicator(){
cCode = null;
iName = null;
iCode = null;
DataList = null;
}
public Indicator(String cCode, String iName, String iCode,ArrayList <MyData> DataList){
this.cCode = cCode;
this.iName = iName;
this.iCode = iCode;
this.DataList = DataList;
}
//setter & getter method for attributes iCode,iName and cCode
//toString method
MyData class:
private int year;
private String value;
public MyData(){
year = 0;
value = null;
}
public MyData(int year, String value){
this.year = year;
this.value = value;
}
//setter & getter method for attributes year and value
//toString method
example of indicator.txt:
(from left: cCode; iName; iCode; values)
MYS; Employment in industry (% of total employment) (modeled ILO estimate); SL.IND.EMPL.ZS;
29,08600044;28,56900024;28,36300087;28,02300072;27,51600075;27,48699951;27,39800072;27,30500031
I think you don't know how to search in a Binary Search Tree. You can do this by going to each node and can use recursion to do so.
In your search() you are taking Indicator as a parameter, but actually you need to take TreeNode because every node has a data of type Indicator which you can access.
In your search() you are calling the search() again and again with same parameters which will not give you results ever. Moreover, you don't have a base case. That's not how recursion work. You will be getting a stackoverflowException(Hahaa, its funny because we are on StackOverFlow). Use this code instead:
public void search(string key)
{
searchHelper(key, root); // root node will be in Tree.java
}
public void searchHelper(string key, TreeNode current)
{
if(current == null)
{
System.out.println("\nCant find !");
return;
}
if(key.compareTo(current.idct.getICode()) < 0 )
searchHelper(key, current.left);
else if(key.compareTo(current.idct.getICode()) > 0)
searchHelper(key,current.right);
else
System.out.println("\n"+current.idct + "Found \n");
}

How to fix a loop for a heap structure

The code compiles but when you run it an error message occurs that gives a null pointer exception. As SEEN in the bottom. the code is supposed to read text from a txt file that is inputted in the program and then create a new txt file with the content of the first txt file sorted by years of service. However, i keep receiving that error message. Any help would be greatly appreciated. I added the error message at the bottom thank you to everyone who is helping your time and effort is greatly appreciated :)
(25 points)Define a Java class called Employee. The class has data members
and accompanying accessor and mutator methods for each of the following six data items. (This involves creating the file Employee.java.)
id (string)
name (string)
salary (double)
department (string)
position (string)
years of service (integer)
(25 points)Create a text (data) file containing data for at least five different
employees (objects). Let each data item sit on its own line in
the text file. For example, the first six lines of the file might look like:
086244
Sally L. Smith
100000.00
Accounting
Manager
7
(50 points)‘Heap’ is a tree-based data-structure that satisfies the heap property. A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node.
By having a heap (or an array that satisfies the heap property), it would be more efficient (generally faster) to perform important tasks on the array such as finding the maximum element in the array (and removing it) and sorting the array.
In this assignment, you will have to write a program that reads a list of employees from a file. The name of the file will be ‘Employee.txt’. The program should output the sorted array to a file called “SortedEmployee.txt”
Heapsort code:
public class HeapSort
{
//heap sort method
public static <Employee extends Comparable<Employee>> void heapSort(Employee[] list)
{
//create a Heap of integers
Heap<Employee> heap = new Heap<>();
//add elements to the heap
for (int i = 0; i< list.length; i++)
heap.add(list[i]);
//remove elements from the heap
for(int i = list.length - 1; i >= 0; i--)
list[i] = heap.remove();
}
}
Heap code:
import java.util.ArrayList;
public class Heap<Employee extends Comparable<Employee>>
{
private ArrayList<Employee> list = new ArrayList<>();
public Heap(){}
public Heap(Employee[] objects)
{
for(int i = 0; i < objects.length; i++)
add(objects[i]);
}
public void add(Employee newObject)
{
list.add(newObject);
int currentIndex = list.size() - 1;
while(currentIndex > 0)
{
int parentIndex = (currentIndex -1)/2;
if(list.get(currentIndex).compareTo(list.get(parentIndex)) > 0)
{
Employee temp = list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
}
else
break;
currentIndex = parentIndex;
}
}
public Employee remove()
{
if(list.size() == 0) return null;
Employee removeObject = list.get(0);
list.set(0, list.get(list.size() -1));
list.remove(list.size() -1);
int currentIndex = 0;
while(currentIndex < list.size())
{
int leftChildIndex = 2 * currentIndex + 1;
int rightChildIndex = 2 * currentIndex + 2;
if(leftChildIndex >= list.size()) break;
int maxIndex = leftChildIndex;
if(rightChildIndex < list.size())
{
if(list.get(maxIndex).compareTo(list.get(rightChildIndex)) < 0)
maxIndex = rightChildIndex;
}
if(list.get(currentIndex).compareTo(list.get(maxIndex)) < 0)
{
Employee temp = list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, temp);
currentIndex = maxIndex;
}
else
break;
}
return removeObject;
}
public int getSize()
{
return list.size();
}
public void print()
{
for (int i = 0; i <= getSize()-1; i++)
{
System.out.print("Index: " + i + " Data: " + list.get(i));
System.out.println();
}
}
}
Employee Object Class:
public class Employee implements Comparable<Employee>
{
private String id;
private String name;
private double salary;
private String department;
private String position;
private int yos;
public Employee(String id, String name, double salary,String department,String position,int yos)
{
this.id = id;
this.name = name;
this.salary = salary;
this.department = department;
this.position = position;
this.yos = yos;
}
public void setid(String id)
{
this.id = id;
}
public void setname(String name)
{
this.name = name;
}
public void setsalary(double salary)
{
this.salary = salary;
}
public void setdepartment(String department)
{
this.department = department;
}
public void setposition(String position)
{
this.position = position;
}
public void setyos(int yos)
{
this.yos = yos;
}
public String getid()
{
return id;
}
public String getname()
{
return name;
}
public double getsalary()
{
return salary;
}
public String getdepartment()
{
return department;
}
public String getposition()
{
return position;
}
public int getyos()
{
return yos;
}
public int compareTo(Employee emp)
{
return (this.yos - emp.yos);
}
public String toString()
{
return "ID=" + this.id+ ", name=" + this.name+ ", salary= $" + this.salary+ ", department:" + this.department+ ", postion:" + this.position+ ",yos= $" + this.yos + "]\n";
}
}
Demo code:
import java.util.*;
import java.io.*;
public class EmployeeDemo
{
public static void main(String[] args)throws IOException
{
Employee[] list = new Employee[5];
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the text file: ");
String fileName = keyboard.nextLine();
File myFile = new File(fileName);
Scanner inputFile = new Scanner(myFile);
//Read all of the values from the file
//and calculate their total
//Read a value from the file
String id = inputFile.nextLine();
String name = inputFile.nextLine();
double salary = inputFile.nextDouble();
String clear = inputFile.nextLine();
String department = inputFile.nextLine();
String position = inputFile.nextLine();
int yrService = inputFile.nextInt();
String llear = inputFile.nextLine();
list[0] = new Employee(id,name,salary,department,position,yrService);
//close the file
// File o = new File("SortedEmployee.txt");
//o.createNewFile();
System.out.println("Enter the file name to be transfered to: ");
String filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(filename);//dont need the top
//HeapSort<Employee> h = new heapSort<Employee>(Employee);
HeapSort.heapSort(list);
//Display the sum of the numbers
while(inputFile.hasNext())//this loop is wrong too
{
outputFile.println(list[0].toString());
}
outputFile.close();
inputFile.close();
System.out.print("File Sorted and Transferred");
}
}
here is the error message i am receiving:
Please enter the text file:
C:\Users\jose385\Desktop\Employee.txt
Enter the file name to be transfered to:
green
Exception in thread "main" java.lang.NullPointerException
at Heap.add(Heap.java:22)
at HeapSort.heapSort(HeapSort.java:13)
at EmployeeDemo.main(EmployeeDemo.java:50)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
You make the List have a size of 5
Employee[] list = new Employee[5];
but only add one element
list[0] = new Employee(id,name,salary,department,position,yrService);
Actually what is the point of only sorting one element
Also try to follow a tutorial on the correct way to implement Comparable

how to get particular element from ArrayList

Hello I am solving this problem given to me where I have to find average salary of a person which has least index id
import java.util.*;
import java.io.*;
public class Main {
public static int processData(ArrayList<String> array) {
for (String elem :array){
System.out.println(elem);
}
return 0;
}
public static void main (String[] args) {
ArrayList<String> inputData = new ArrayList<String>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader("input.txt")));
while(in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
inputData.add(line);
}
int retVal = processData(inputData);
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
output.println("" + retVal);
output.close();
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
}
}
}
the program is accepting input from text file as follows
282, ij, 11, 1600000
273, cbg, 12, 800000
567, nj, 11, 800000
539, cb, 11, 600000
So the output will be
11 520000
I am able to print the elements from array list but not been able to access particular elements. Can anyone help me to access particular element which is, in this case, 11,160000 and so on?
Thank you in advance
Hint
You can calculate the AVG of the index 11 like this :
public static int processData(ArrayList<String> array) {
String[] spl;
int avg = 0, nbr = 0;
for (String elem : array) {
//split your String with ", " and space
spl = elem.split(", ");
//the index exist in the 3ed position, so you have to check your index if 11 then you can get its value
if(spl[2].equals("11")){
avg+=Integer.parseInt(spl[3]);
nbr++;
}
System.out.println(elem);
}
System.out.println((avg/nbr));
return avg / nbr;
}
When you print in your code you have to use :
output.println("11 " + retVal);
Hope this can gives you an idea.
You create a List of String to store employee data that contains multiple fields.
You should not as it mixes data employees.
The general idea I propose you :
1) Instead of storing all information in a List of String, use a List of Employee.
replace
ArrayList<String> inputData = new ArrayList<String>();
by
List<Employee> employees = new ArrayList<Employee>();
2)Use each read line that represents a person to create a instance of a custom Object, for example Employee.
So replace
inputData.add(line);
by something like that
String[] token = line.split(",");
Employee employee= new Employee(Integer.valueOf(token[0]),token[1],Integer.valueOf(token[2]),Integer.valueOftoken[3]));
employees.add(employee);
3) During this iteration to read the file, you can store in a variable that is the Employee with the minimum id.
4) After reading the file, you know the Employee with the minimum id. So you can iterate on the List of Employee and sum the salaries of the Employee that has this id and count the number of salary for this Employee.
When the loop is finished compute the avg : float avg = sum / (float)count;
It is not the most optimized way but it makes the job.
The following code will do what you need.
public class MyMain {
private static String inputFilePath = "/path/to/input.txt";
private static String outputFilePath = "/path/to/output.txt";
public static int processData(ArrayList<MyData> array) {
if (array.size() > 0) {
int minId = array.get(0).getData3();
for (MyData elem : array) {
if(elem.getData3() < minId) {
minId = elem.getData3();
}
}
int count = 0;
int total = 0;
for (MyData myData : array) {
if(myData.getData3() == minId) {
count++;
total += myData.getData4();
}
}
System.out.println("Min ID : " + minId + " -- Avg Sal : " + total/count);
}
return 0;
}
public static void main(String[] args) {
ArrayList<MyData> inputData = new ArrayList<>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader(inputFilePath)));
while (in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
inputData.add(new MyData(line));
}
int retVal = processData(inputData);
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(outputFilePath)));
output.println("" + retVal);
output.close();
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
}
}
}
class MyData {
int data1;
String data2;
int data3;
int data4;
public MyData() {
// TODO Auto-generated constructor stub
}
public MyData(String data) {
String dataArr[] = data.split(",");
this.data1 = Integer.parseInt(dataArr[0].trim());
this.data2 = dataArr[1].trim();
this.data3 = Integer.parseInt(dataArr[2].trim());
this.data4 = Integer.parseInt(dataArr[3].trim());
}
public int getData1() {
return data1;
}
public void setData1(int data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public int getData3() {
return data3;
}
public void setData3(int data3) {
this.data3 = data3;
}
public int getData4() {
return data4;
}
public void setData4(int data4) {
this.data4 = data4;
}
}

Creating node with weight in java graph

I am creating a program to create a graph for bibliography dataset. The graph is directed, has Author node and Paper node, and has 2 types of edges (author to paper edge, paper to paper edge).
I want to get an input from you about whether or not what I am creating is making sense. Right now, it produces the right result when I want to get the outEdge and inEdge from and to a node. But im not sure if this implementation is correct in terms of the methods, designs, and algorithm.
Also, I have a problem with assigning weight to a node. I want to ask how can I do this as well. Right now, what I have tried is as follows:
for (String item : CandidateAuthorType1Unique) {
double weight = Collections.frequency(CandidateAuthorType1, item);
n.setWeight(item,weight);;
System.out.println(n.getName() + " : " + n.getWeight());
}
However, after using setWeight, the getName() method returns null. This means that the weight assigned is not assigned to a certain item. I wonder how to update the weight a certain item.
If I use
for (String item : CandidateAuthorType1Unique) {
double weight = Collections.frequency(CandidateAuthorType1, item);
n = new Node(item,weight);
System.out.println(n.getName() + " : " + n.getWeight());
}
Does it mean that each time a new node n is created, the old n node will not be stored? How can I checked every node ever created and its weight?
I would like to ask for your input to this program. Any input would be really helpful for me. Thank you.
Main class: Ranker.java
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.sql.*;
public class Ranker {
static Graph g;
static Node n;
static Edge e;
static HashMap nodeMap; // maps Integer NodeIDs to Node object
String id;
double weight;
Ranker() {
g = new Graph();
nodeMap = new HashMap();
n = new Node(id,weight);
}
public static void main (String[] args) throws ClassNotFoundException, SQLException, IOException, IllegalArgumentException, IllegalAccessException{
Ranker Ranker = new Ranker();
Connection connect = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
HashMap nodeMap = new HashMap(); // maps Integer NodeIDs to Node objects
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/arnetminer?"+"user=root&password=1234");
preparedStatement = connect.prepareStatement("Select fr,t,ty from subedge");
resultSet = preparedStatement.executeQuery();
int i=0;
while(resultSet.next()) {
g.addEdgeForIndexing(resultSet.getInt(1),resultSet.getInt(2),resultSet.getInt(3));
i++;
System.out.println( "edges added to G = "+i);
}
System.out.println("Loaded " + g.nodeCount() + " nodes.");
buildNodes();
System.out.println("Enter first author key:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String authorkey1 = br.readLine();
int authorID1 = Integer.parseInt(authorkey1);
String AuthorID1 = "A"+authorID1;
ArrayList<String> p1 = g.getOutEdgesToP(AuthorID1);
System.out.println("P1 = " + p1);
ArrayList<String> p2 = new ArrayList<String>();
for (int j = 0; j<p1.size();j++){
ArrayList<String> temp = g.getOutEdgesToP(p1.get(j));
if (temp!=null)
p2.addAll(temp);
}
System.out.println("P2 = " +p2);
ArrayList<String> CandidateAuthorType1 = new ArrayList<String>();
for (int k = 0; k<p2.size(); k++){
ArrayList<String> temp = g.getInEdgesFromPtoA(p2.get(k));
if(temp!=null)
CandidateAuthorType1.addAll(temp);
}
System.out.println("Candidate Author Type 1= " + CandidateAuthorType1);
ArrayList<String> CandidateAuthorType1Unique = removeDuplicates(CandidateAuthorType1);
System.out.println("-----------------------------------------------");
System.out.println("Candidate author type 1 and author node weight:");
for (String item : CandidateAuthorType1Unique) {
double weight = Collections.frequency(CandidateAuthorType1, item);
n.setWeight(item,weight);;
System.out.println(n.getName() + " : " + n.getWeight());
}
ArrayList<String> CandidatePaperType1 = new ArrayList<String>();
for (int l = 0; l<CandidateAuthorType1.size(); l++){
ArrayList<String> temp = g.getOutEdgesToP(CandidateAuthorType1.get(l));
if(temp!=null)
CandidatePaperType1.addAll(temp);
}
System.out.println("Candidate Paper Type 1= " + CandidatePaperType1);
}
private static ArrayList<String> removeDuplicates(ArrayList<String> element){
ArrayList<String> result = new ArrayList<>();
HashSet<String> set = new HashSet<>();
for (String item : element) {
if (!set.contains(item)) {
result.add(item);
set.add(item);
}
}
return result;
}
private static void buildNodes()
{
String nodeID;
double weight = 0;
Node n;
Iterator it = g.nodeIteratorInitial();
while (it.hasNext()) {
nodeID = (String) it.next();
if (!nodeMap.containsKey(nodeID)){
n = new Node(nodeID,weight);
nodeMap.put(nodeID, 0);
}
}
}
}
Graph.java
import java.lang.reflect.Field;
import java.util.*;
public class Graph {
private HashSet<String> nodeIDs;
public HashMap<Integer, String> nodeIDsWithTN;
public HashMap<Integer, String> TNMap;
private HashMap<String, ArrayList<String>> edges;
private HashMap<String, ArrayList<String>> reverse;
private int numNodes;
private int numEdges;
private int numReverse;
public Graph() {
edges = new HashMap<String, ArrayList<String>>();
reverse = new HashMap<String, ArrayList<String>>();
nodeIDs = new HashSet<String>();
nodeIDsWithTN = new HashMap<Integer, String>();
TNMap = new HashMap<Integer, String>();
new HashSet();
}
public void addEdgeForIndexing(int from, int to, int T) throws IllegalArgumentException, IllegalAccessException {
String From = ""+from;
String To = ""+to;
int type = T;
if(T==1)
{
From="A"+from;
To="P"+to;
}
else if(T==2)
{
From="P"+from;
To="P"+to;
}
else
System.out.println("T ="+T+" value undefined");
Edge e = new Edge(From,To,type);
nodeIDs.add(e.From);
nodeIDs.add(e.To);
ArrayList<String> tmp = null;
if (edges.containsKey(e.From))
tmp = (ArrayList<String>) edges.get(e.From);
else {
tmp = new ArrayList<String>();
edges.put(e.From,tmp);
}
tmp.add(e.To);
ArrayList<String> tmp2 = null;
if (reverse.containsKey(e.To))
tmp2 = (ArrayList<String>) reverse.get(e.To);
else {
tmp2 = new ArrayList<String>();
reverse.put(e.To,tmp2);
}
tmp2.add(e.From);
}
public int nodeCount() {
if(nodeIDs.size() > 0)
return nodeIDs.size();
// else return numNodes;
return numEdges;
}
public int countInEdges(Integer key) {
if (!reverse.containsKey(key)) return 0;
return ((ArrayList<?>) reverse.get(key)).size();
}
public int countOutEdges(Integer key) {
if (!edges.containsKey(key)) return 0;
return ((ArrayList<?>) edges.get(key)).size();
}
public ArrayList<String> getInEdgesFromPtoA(String id) {
if (!reverse.containsKey(id)) return null;
ArrayList<String> a = reverse.get(id);
ArrayList<String> result = new ArrayList<String>();
for(int j=0;j<a.size();j++){
if(a.get(j).startsWith("A")){
result.add(a.get(j));
}
}
return result;
}
public ArrayList<String> getOutEdgesToP(String id) {
if (!edges.containsKey(id)) return null;
ArrayList<String> a = edges.get(id);
ArrayList<String> result = new ArrayList<String>();
for(int j=0;j<a.size();j++){
if(a.get(j).startsWith("P")){
result.add(a.get(j));
}
}
return result;
}
public Iterator<String> nodeIteratorInitial() {
return nodeIDs.iterator();
}
}
Edge.java
public class Edge {
String From;
String To;
int type;
private static int counter = 0;
public Edge(String From, String To, int type) {
this.From = new String(From);
this.To = new String(To);
this.type = type;
// System.out.println("edges added from " + From + " to " + To + " with type "+ type);
}
public String getFrom(){
return From;
}
public String getTo(){
return To;
}
public int getType(){
return type;
}
public void setFrom(String From){
this.From = From;
}
public void setTo(String To){
this.To = To;
}
public void setType(int type){
this.type = type;
}
}
Node.java
public class Node {
String id;
double weight;
private static int counter = 0;
public Node(String id,double weight) {
this.id = id;
this.weight = weight;;
}
public double getWeight(){
return weight;
}
public String getName() {
return id;
}
public void setWeight(String id, double weight){
if (this.id==id){
this.weight=weight;}
System.out.println("The node " + id + " has weight " + weight);
}
public void setName(String id){
this.id=id;
}
}
As you are initialising n in the Ranker() constructor, when the constructor is called, the String id has not been assigned and therefore always contains the value null. Therefore your Node n also gets the id as null. This is the reason why the weight isn't updated as in your setWeight(String id, double weight) function, the new id is compared to null which always returns false therefore the weight doesn't get updated.
You could make the following changes in your code
1) Remove the n = new Node(id,weight) initialisation in your Ranker() constructor.
2) Add the following lines instead of n.setWeight(item,weight) in your main method in Ranker class.
if (n == null)
n = new Node(item, weight);
n.setWeight(item, weight);

Writing on an output file

I am stuck on this part where it does not write to an output file
the first class is contact I had to modify this is not my class is the authors class
I just had to use it
//********************************************************************
// Contact.java Author: Lewis/Loftus
//
// Represents a phone contact.
//********************************************************************
public class Contact implements Comparable
{
private String firstName, lastName, phone;
//-----------------------------------------------------------------
// Constructor: Sets up this contact with the specified data.
//-----------------------------------------------------------------
public Contact (String first, String last, String telephone)
{
firstName = first;
lastName = last;
phone = telephone;
}
//-----------------------------------------------------------------
// Returns a description of this contact as a string.
//-----------------------------------------------------------------
public String toString ()
{
return lastName + ", " + firstName + "\t" + phone;
}
//-----------------------------------------------------------------
// Returns true if the first and last names of this contact match
// those of the parameter.
//-----------------------------------------------------------------
public boolean equals (Object other)
{
return (lastName.equals(((Contact)other).getLastName()) &&
firstName.equals(((Contact)other).getFirstName()));
}
//-----------------------------------------------------------------
// Uses both last and first names to determine ordering.
//-----------------------------------------------------------------
public int compareTo (Object other)
{
int result;
String otherFirst = ((Contact)other).getFirstName();
String otherLast = ((Contact)other).getLastName();
if (lastName.equals(otherLast))
result = firstName.compareTo(otherFirst);
else
result = lastName.compareTo(otherLast);
return result;
}
//-----------------------------------------------------------------
// First name accessor.
//-----------------------------------------------------------------
public String getFirstName ()
{
return firstName;
}
//-----------------------------------------------------------------
// Last name accessor.
//-----------------------------------------------------------------
public String getLastName ()
{
return lastName;
}
}
this class oes the sorting this is fine. it does the sorting no prblem
public class Sorting {
public static void bubbleSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[i + 1]) > 0)
{ //swap check
Comparable tmp = data[i];
data[i] = data[i + 1];
data[i + 1] = tmp;
}
}
bubbleSortRecursive(data, lastIndex);
}
}
public static void selectionSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
int largestIndex = lastIndex;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[largestIndex]) > 0)
{
largestIndex = i;
}
}
if (largestIndex != lastIndex)
{ //swap check
Comparable tmp = data[lastIndex];
data[lastIndex] = data[largestIndex];
data[largestIndex] = tmp;
}
selectionSortRecursive(data, n - 1);
}
}
}
this is the part I need help with. It is not outputing to he p4output.txt, i dont know what the problem is.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestProject4 {
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
}
private static void doBubbleSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.bubbleSortRecursive(contacts, contacts.length);
System.out.println("\nAfter bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void doSelectionSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.selectionSortRecursive(contacts, contacts.length);
System.out.println("\nAfter selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void printContacts(Contact[] contacts)
{
try
{
// this part I need help with it is not outputing in the text file
File file = new File("p4output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (Contact contact : contacts)
{
bw.write(contact.toString());
}
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("\t" + contacts);
}
public static Contact[] createContacts()
{
return new Contact[]
{
new Contact("John" , "Smith" , "610-555-7384"),
new Contact("Sarah" , "Barnes" , "215-555-3827"),
new Contact("Mark" , "Riley", "333-333-3333"),
new Contact("Laura" , "Getz" ,"663-555-3984"),
new Contact("Larry" , "Smith" , "464-555-3489"),
new Contact("Frank" , "Phelps" , "322-555-2284"),
new Contact("Mario" , "Guzman" , "804-555-9066"),
new Contact("Marsha" , "Grant" , "243-555-2837"),
};
}
}
According to Eclipse, you never call/use printContacts(Contact[] contacts); method
Your printContacts(Contact[] contacts); contains the statements to write a file.
You don't appear to call the function printContacts() in your program. Try calling it after you do your contact creation and sorting.
It might look like this:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
printContacts(contactArray);//inserted code
}
Also, when you call your sorting methods, doSelectionSortRecursive(), you don't return the list of contacts. Make a return statement for it and then put the contact array into your printContacts function.
Here's an example:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
Contact[] contacts = doSelectionSortRecursive();
printContacts(contacts);
}
public static Contact[] doSelectionSortRecursive(){
Contact[] contacts = createContacts();
//your sorting code
return contacts;
}
Using this method allows you to get the array of contacts from the method once it has been sorted.

Categories