I have private class node inside public class singlyLinkedList and I want to move through the List (as temp) from another public class, so how I can creat temporary Node or(method) to move through the List.
and I can't change the class Node to public and I should keep to private.
the idea of programming is:
the read data from file in TextAnalyzer class, then insert it in SinglyLinkedList with counting the frequency of words.
class singlyLinkedList
public class SinglyLinkedList<T> {
private static class Node<T> {
public T data;
Node<T> next;
public Node(T data) {
this.data = data;
next = null;
}
}
Node<T> head;
Node<T> tail;
int size;
public SinglyLinkedList() {
head = null;
tail = null;
size = 0;
}
public void insert(T S) {
Node<T> temp = new Node<T>(S);
if (head == null) {
head = tail = temp;
size++;
return;
}
temp.next = head;
head = temp;
size++;
return;
}
public void display() {
Node<T> tmp = head;
while (tmp != null) {
System.out.println(tmp.data.toString());
tmp = tmp.next;
}
The class TextAnalyzer
SinglyLinkedList<WData> list = new SinglyLinkedList<WData>();
private static class WData {
String word;
int freq;
public WData(String w, int f) {
word = w;
freq = f;
}
// .. Add other methods here as needed
#Override
public String toString() {
// if(list.)
return "WData{" + "word=" + word + " , freq=" + freq + '}';
}
}
public Scanner sc;
public void processText(String filename) {
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
String line = sc.next();
String[] st = line.split(" ");
for (int i = 0; i < st.length; i++) {
processWord(st[i]);
}}
list.display();
} catch (FileNotFoundException ex) {
System.out.println("error in loadstudends Scanner");
}
}
public void processWord(String word) {
Node<WData> temp = list.head;
while (temp != null) {
if (temp.data.word.equalsIgnoreCase(word)) {
break;
}
temp = temp.next;
}
if (temp == null || Dtemp.data.word.matches(".*\\d.*")) {
list.insert(new WData(word, 1));
} else {
temp.data.freq += 1;
}
}}
we can't creat node temp because class node is private, so I couldn't go for the loop
You may want to do the following
1. Create your own Iterator implementation within SinglyLinkedList
public class MyIterator implements Iterator<T> {
private Node<T> next = head;
private Node<T> current = null;
#Override
public boolean hasNext() {
return next != null;
}
#Override
public T next() {
if (hasNext()) {
current = next;
next = current.next;
return current.data;
}
throw new NoSuchElementException();
}
#Override
public void remove() {
//TODO
}
}
Make SinglyLinkedList to implement Iterable
public class SinglyLinkedList<T> implements Iterable<T> {
return instance of iterator created in 1 when iterator() is invoked
#Override
public Iterator<T> iterator() {
return new MyIterator();
}
Use for each loop in your Text Analyzer class
I am having a problem here. I am trying to add more than one line when reading from text file and adding item to linked list, but for some reason it stops after the first line. This program reads a file line by line splits each word into an array and adds that object to a linked list. When I print it only prints the first line of the text file.
package com.foodlist;
public class Food {
private String name;
private String group;
private int calories;
private double percentage;
public Food(String name, String group, int calories, double percentage){
this.name = name;
this.group = group;
this.calories = calories;
this.percentage = percentage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getCalories() {
return calories;
}
public void setCalories(int calories) {
this.calories = calories;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public String toString(){
String result = "";
result = name + " " + group + " " + calories + " " + percentage + "\n";
return result;
}
}public class FoodList {
private FoodListNode head;
private class FoodListNode{
public Food f;
public FoodListNode next;
public FoodListNode(Food f){
this.f = f;
this.next = null;
}
}
public FoodList(){
head = null;
}
public FoodList getFoodList(){
final String FILE_NAME = "foods.txt";
String[] item = null;
Scanner inFile = null;
try {
inFile = new Scanner(new File(FILE_NAME));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FoodList list = new FoodList();
while (inFile.hasNextLine()){
String line = inFile.nextLine().trim();
item = line.split("\\s+");
if(item.length==4){
list.add(new Food(item[0], item[1], Integer.parseInt(item[2]), Double.parseDouble(item[3])));
}
}
inFile.close();
return list;
}
public void add(Food f){
FoodListNode node = new FoodListNode(f);
if (head == null){
head = node;
}
else{
FoodListNode tmp = head;
while (tmp.next != null){
tmp = tmp.next;
tmp.next = node;
}
}
}
public String toString(){
String result = "";
FoodListNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next){
result += tmp.f;
}
return result;
}
}
public class FoodMenu {
public static void main(String[] args) {
FoodList items = new FoodList();
FoodList list = items.getFoodList();
System.out.println(list);
}
}
The problem was the braces I put in the while loop here:
if (head == null){
head = node;
} else {
FoodListNode tmp = head;
while (tmp.next != null)->{
tmp = tmp.next;
tmp.next = node;
}<-
}
I removed them and now it is working perfectly. Have not looked into why this change fixed it, but will look into it more.
For an assignment, I've been tasked to create a priority based support ticket system which contains the user's Name, ID, Handler and Priority however ticket's with higher priority are placed first in the list to be dealt with.
I have three classes.
Main: where I add/delete and change ticket priority.
TicketSystem: Contains the constructor for the ticket alongside getters and setter methods
LinkedList: Has insert, delete printList and should have sortList
So far I've determined the algorithm needs to be bubblesort as Priority is an int value but I'm not too sure how to receive the value for priority and then sort it.
public class TicketSystem {
private String handler;
private int priority;
private String iD;
private String creator;
public TicketSystem() {
}
public String getHandler ( ) {
return handler;
}
public int getPriority () {
return priority;
}
public String getID () {
return iD;
}
public String creator () {
return creator;
}
public void setID (String i) {
this.iD = i;
}
public void setHandler (String h) {
this.handler = h;
}
public void setPriority (int p ) {
this.priority = p;
}
public String setCreator (String c) {
return this.creator = c;
}
public void addTicket( String h, int p, String c, String iD) {
this.handler = h;
this.priority = p;
this.iD = iD;
this.creator = c;
}
#Override
public String toString() {
String output = "";
output += "Handler: " + handler +", ";
output += "Priority: " + priority + ", ";
output += "Creator: " + creator + ", ";
output += "ID: " + iD + " ";
return output;
}
}
public class LinkedList {
private Node head;
public LinkedList(TicketSystem ticket) {
head = new Node();
head.ticket = ticket;
head.link = null;
}
public boolean insertItem(TicketSystem ticket) {
Node n = new Node();
Node new_node;
new_node = head;
while (new_node.link != null) {
new_node = new_node.link;
}
n.ticket = ticket;
n.link = null;
new_node.link = n;
return true;
}
public void printList() {
Node z = head;
while (z!= null) {
System.out.println(z.ticket.toString());
z = z.link;
}
}
public boolean deleteItem(TicketSystem ticket) {
if(ticket.equals(head.ticket)) {
head = head.link;
return true;
} else {
Node prevNode = head;
Node curNode = head.link;
while(curNode != null && !(curNode.ticket == ticket)) {
prevNode = curNode;
curNode = curNode.link;
}
if(curNode != null) {
prevNode.link = curNode.link;
return true;
} else {
return false;
}
}
}
/* sort list */
public void sortList() {
TicketSystem ts = new TicketSystem();
}
class Node {
private TicketSystem ticket;
private Node link;
}
}
So I am trying to organize and array of strings in alphabetical order and insert them into a binary tree.
I first took in a text file and used scanner to read it into a string.
I then stripped away all punctuation and made all of the letters lowercase.
Finally I turned my string into and array of words and sorted them using Arrays.sort().
however when I run the program to see if I can print my list, the only output I get is:
[Ljava.lang.String;#4965391b
I'm not sure what this means or why I am getting it as an output please help.
my code is below.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Tester {
public static void main(String[] args) throws FileNotFoundException {
Tester run = new Tester();
run.it();
}
public void it() throws FileNotFoundException {
BTree theTree = new BTree();
String str = this.readInFile();
str = stripPunctuation(str);
String myWords [] = breakIntoWords(str);
//theTree.print();
}
public String readInFile() throws FileNotFoundException {
String myFile = "";
int numWords = 0;
Scanner myScan = new Scanner(new File("Dracula.txt"));
while(myScan.hasNext() == true) {
myFile += myScan.nextLine() + " ";
}
return myFile;
}
public String stripPunctuation(String myFile) {
myFile.replace('.', ' ');
myFile.replace(',', ' ');
myFile.replace('!', ' ');
myFile.replace('?', ' ');
myFile.replace('(', ' ');
myFile.replace(')', ' ');
myFile.replace('"', ' ');
myFile.replace('[', ' ');
myFile.replace(']', ' ');
myFile.toLowerCase();
return myFile;
}
public String [] breakIntoWords(String myFile) {
BTree thisTree = new BTree();
String[] words = myFile.split("\\s+");
Arrays.sort(words);
System.out.print(words);
return words;
}
}
public class BTNode {
private BTNode rightChild;
private BTNode leftChild;
private String myWord;
private int numWords;
private int numInstance;
private boolean uniqueWord;
private boolean isRoot;
private boolean isDeepest;
public BTNode(String myWord, int numWords){
this.numInstance = 1;
this.myWord = myWord;
this.numWords = numWords;
this.rightChild = null;
this.leftChild = null;
}
public String getMyWord() {
return myWord;
}
public void setMyWord(String myWord) {
this.myWord = myWord;
}
public BTNode getRightChild() {
return rightChild;
}
public void setRightChild(BTNode rightChild) {
this.rightChild = rightChild;
}
public BTNode getLeftChild() {
return leftChild;
}
public void setLeftChild(BTNode leftChild) {
this.leftChild = leftChild;
}
public int getnumWords() {
return numWords;
}
public void setnumWords(int numWords) {
this.numWords = numWords;
}
public boolean isUniqueWord() {
return uniqueWord;
}
public void setUniqueWord(boolean uniqueWord) {
this.uniqueWord = uniqueWord;
}
public boolean isRoot() {
return isRoot;
}
public void setRoot(boolean isRoot) {
this.isRoot = isRoot;
}
public boolean isDeepest() {
return isDeepest;
}
public void setDeepest(boolean isDeepest) {
this.isDeepest = isDeepest;
}
public int getNumInstance() {
return numInstance;
}
public void setNumInstance(int numInstance) {
this.numInstance = numInstance;
}
}
public class BTree {
private BTNode root;
private int nodeCount;
public boolean add(String word, int numWords){
BTNode myNode = new BTNode(word, numWords);
if(root == null){
root = myNode;
nodeCount++;
return true;
}
if(findNode(word)){
int tmp = myNode.getNumInstance();
tmp++;
myNode.setNumInstance(tmp);
return false;
}
BTNode temp = root;
while(temp != null){
if(word.compareTo(temp.getMyWord()) < 0) {
if(temp.getRightChild() == null){
temp.setLeftChild(myNode);
nodeCount++;
return true;
} else {
temp = temp.getRightChild();
}
} else {
if(temp.getLeftChild() == null){
temp.setLeftChild(myNode);
nodeCount++;
return true;
} else {
temp = temp.getLeftChild();
}
}
}
return false;
}
public boolean findNode(String word) {
return mySearch(root, word);
}
private boolean mySearch(BTNode root, String word) {
if (root == null) {
return false;
}
if ((root.getMyWord().compareTo(word) < 0)) {
return true;
} else {
if (word.compareTo(root.getMyWord()) > 0) {
return mySearch(root.getLeftChild(), word);
} else {
return mySearch(root.getRightChild(), word);
}
}
}
public void print() {
printTree(root);
}
private void printTree(BTNode root) {
if (root == null) {
System.out.print(".");
return;
}
printTree(root.getLeftChild());
System.out.print(root.getMyWord());
printTree(root.getRightChild());
}
public int wordCount() {
return nodeCount;
}
}
You are printing an Array of Strings in System.out.print, so basically [Ljava.lang.String;#4965391b is the string representation of the reference to this array.
If you replace the part
System.out.print(words);
with
for (String word : words) {
System.out.println(" " + word);
}
you will get the elements inside the Array.
I need help to generate a graph's link connection in json format which are index numbers. I can manage to generate the 1st part of nodes index numbers but can't do the 2nd part of links index numbers. Nodes index number should be plotted links index no. Anyone please help.
Input file:
Abdelaziz Bouteflika,Bush,1
Albert II of Belgium,Bush,1
Albert Wehrer,Bush,1
Berlusconi,Bush,1
Bernard-Montgomery,Bush,1
Bush,Fidel-Castro,1
Bernard-Montgomery,Albert Wehrer,5
Expected Output file:
{
"nodes":[
{"name":"Bush","Id":0},
{"name":"Abdelaziz Bouteflika","Id":1},
{"name":"Albert II of Belgium","Id":2},
{"name":"Albert Wehrer","Id":3},
{"name":"Berlusconi","Id":4},
{"name":"Bernard-Montgomery","Id":5},
{"name":"Fidel-Castro","Id":6}
],
"links":[
{"source":1,"target":0},
{"source":2,"target":0},
{"source":3,"target":0},
{"source":4,"target":0},
{"source":5,"target":0},
{"source":6,"target":0},
{"source":5,"target":3}
]
}
My code:
public class Link_Of_Index {
List<String> linklist1 = new ArrayList<String>();
List<String> finalList = new ArrayList<String>();
public void getIndexNo() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("E:/Workspace/Entity_Graph_Creation/WebContent/Graph_nodes_1.csv"));
FileWriter fw = new FileWriter(new File("E:/workspace/Entity_Graph_Creation/Input/links.json"));
try{
String line = null;
int index=0;
while (( line = reader.readLine()) != null)
{
String[] splits = line.split(",");
linklist1.add(splits[0]);
linklist1.add(splits[1]);
linklist1.add(splits[2]);
}
for (String s: linklist1) {
if (!finalList.contains(s)) {
finalList.add(s);
JSONObject obj = new JSONObject();
obj.put("Id", index);
obj.put("name", s);
fw.write(obj.toString()+ ","+ "\n");
index ++;
}
fw.flush();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Link_Of_Index inx = new Link_Of_Index();
inx.getIndexNo();
}
}
EDIT: I rewrote the entire answer to reflect your new requirements. For the next time, you should mention that in first place, or make 2 seperate questions of it.
public class GraphFileIO {
private static final Comparator<Node> NODE_COMPARATOR = new Comparator<Node>() {
#Override
public int compare(Node node1, Node node2) {
return node1.compareTo(node2);
}
};
private Map<Node, List<Edge>> graph;
private final File sourceFile;
public GraphFileIO(final File pSource) throws IOException {
if (pSource.exists()) {
sourceFile = pSource;
} else {
throw new IOException();
}
}
public void readGraph() throws IOException {
int index = 1;
graph = new TreeMap<>(NODE_COMPARATOR);
for (String line : Files.readAllLines(sourceFile.toPath(), Charset.defaultCharset())) {
if (line.trim().isEmpty()) {
continue; // skip blank lines
}
// csv columns:
// node 1, node 2, weight, event
String[] splits = line.split(",");
Node n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
Edge edge = new Edge(splits[3]);
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
Node node = entry.getKey();
if (node.getName().equals(splits[0])) {
edge.setSource(node.getId());
entry.getValue().add(edge);
} else if (node.getName().equals(splits[1])) {
edge.setTarget(node.getId());
// if edges are bi-directional, uncomment the next line of
// code
/* entry.getValue().add(edge); */
}
}
}
}
public void writeGraphToFile(final File targetFile) throws IOException {
JSONObject obj = new JSONObject();
JSONArray nodeList = new JSONArray();
JSONArray edgeList = new JSONArray();
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
JSONObject jsonNode = new JSONObject();
jsonNode.put("name", entry.getKey().getName());
jsonNode.put("Id", entry.getKey().getId());
jsonNode.put("event", entry.getValue());
nodeList.add(jsonNode);
for (Edge link : entry.getValue()) {
JSONObject link = new JSONObject();
link.put("source", link.getSourceID());
link.put("target", link.getTargetID());
edgeList.add(link);
}
}
obj.put("nodes", nodeList);
obj.put("links", edgeList);
FileWriter fw = new FileWriter(targetFile);
fw.write(obj.toJSONString());
fw.flush();
fw.close();
}
public static void main(final String[] args) {
File source = new File("C:\\Sandbox\\src\\foo\\test.csv");
File target = new File("C:\\Sandbox\\src\\foo\\testresult.csv");
GraphFileIO g;
try {
g = new GraphFileIO(source);
g.readGraph();
g.writeGraphToFile(target);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Node implements Comparable<Node> {
private final Integer id;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
private final String name;
private final Collection<String> events;
public Node(Integer id, String name) {
super();
this.id = id;
this.name = name;
this.events = new HashSet<>();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public Collection<String> getEvents() {
return events;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Node other = (Node) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
#Override
public int compareTo(Node o) {
return id.compareTo(o.id);
}
}
public class Edge {
private final String event;
private Integer sourceID;
private Integer targetID;
public Edge(String string) {
event = string;
}
public void setSource(Integer id) {
sourceID = id;
}
public void setTarget(Integer id) {
targetID = id;
}
#Override
public String toString() {
return event;
}
public Integer getSourceID() {
return sourceID;
}
public Integer getTargetID() {
return targetID;
}
public String getEvent() {
return event;
}
}