I am trying to acheive JSON to JSON conversion in java based on the specification given on runtime.
Example : if at runtime source : com.gsdetails.gname,target : com.track.trackName (i.e source field should be mapped to target field in generated JSON)
My approach was to create N-array tree for the specification part and do breadth first travesal (get queue with it to craeate structure for resulting json)
I am using Jackson api to create tree from input JSON and traversing both queue(bfs) and input tree to create resulting json.
Unable to get expected output
PS : I thought of using JOLT api but it will not serve my purpose
Tree (for specification)
public class TrieBuilder {
public static void main(String[] args) throws Exception {
createSpec();
}
public static Trie createSpec() throws Exception {
BufferedReader reader = new BufferedReader(
new FileReader(""));
String currentLine = reader.readLine();
Trie trie = new Trie();
while (currentLine != null) {
String[] lines = currentLine.split(",");
String sourceLine = lines[0];
String targetLine = lines[1];
String sourcePath = sourceLine.split("=")[1];
String targetPath = targetLine.split("=")[1];
trie.insertWord(sourcePath.trim(), targetPath.trim());
currentLine = reader.readLine();
}
return trie;
}
}
class TrieNode {
String source;// consider this as content/reference point of a tree
String target;
boolean isEnd;
int count;
List childList;
boolean isRoot;
/* Constructor */
public TrieNode(String source, String target) {
childList = new ArrayList<TrieNode>();
isEnd = false;
count = 0;
this.source = source;
this.target = target;
}
public TrieNode subNodeWord(String word) {
if (childList != null) {
for (TrieNode eachChild : childList)
if (eachChild.source.equals(word))
return eachChild;
}
return null;
}
}
class Trie {
public TrieNode root;
/* Constructor */
public Trie() {
root = new TrieNode("", "");
}
public void insertWord(String sourceWords, String targetWords) {
if (searchWord(sourceWords) == true)
return;
TrieNode current = root;
String[] sourceArray = sourceWords.split(":");
String[] targetArray = targetWords.split(":");
for (int i = 0; i < sourceArray.length; i++) {
TrieNode child = current.subNodeWord(sourceArray[i]);
if (child != null) {
current = child;
} else {
current.childList.add(new TrieNode(sourceArray[i],
targetArray[i]));
current = current.subNodeWord(sourceArray[i]);
}
current.count++;
}
current.isEnd = true;
}
public boolean searchWord(String words) {
TrieNode current = root;
for (String word : words.split(":")) {
if (current.subNodeWord(word) == null) {
return false;
} else {
current = current.subNodeWord(word);
}
}
if (current.isEnd == true)
return true;
return false;
}
public Queue<TrieNode> bfsTraversal(TrieNode node) {
// TODO need to add logic for bfs/dfs for traversing the trie
Queue<TrieNode> queue = new LinkedList<>();
Queue<TrieNode> tempQueue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TrieNode tempNode = queue.poll();
tempQueue.add(tempNode);
int counter = tempNode.childList.size(), i = 0;
if (tempNode == null)
break;
if (!tempNode.source.isEmpty())
System.out.println("Source :" + tempNode.source
+ " Target : " + tempNode.target);
while (i < counter) {
queue.add(tempNode.childList.get(i++));
}
}
tempQueue.poll();
return tempQueue;
}
Source to target mapping file :
source = com:track:trackDetails:fname, target = gsUser:gsProp:gsDetails:gsFirstName
source = com:track:trackDetails:lname, target = gsUser:gsProp:gsDetails:gsLastName
helper class (Actual transform):
public class JsonHelperClass{
// private Files file = null;// create a tempfile
private JsonNodeFactory factory;
private JsonFactory jsonFactory;
private ObjectMapper mapper;
private JsonNode jsonRoot;
private Queue<TrieNode> queue;
// private JsonParser jsonParser =
public JsonHelperClass() throws JsonProcessingException, IOException {
this.factory = JsonNodeFactory.instance;
this.jsonFactory = new JsonFactory();
this.mapper = new ObjectMapper();
this.jsonRoot = mapper.readTree(new File("json with data"));
}
public static void main(String[] args) throws Exception, Exception {
JsonHelperClass helperClass = new JsonHelperClass();
helperClass.jsonCreator();
ObjectNode objectNode = null;
ObjectNode result = helperClass.createJsonRecursively(objectNode);
System.out.println(result.toString());
}
public void jsonCreator() throws Exception {
Trie trie = TrieBuilder.createSpec();
queue = trie.bfsTraversal(trie.root);
}
public ObjectNode createJsonRecursively(ObjectNode outputJson) throws Exception {
TrieNode nodeOfQueue = queue.poll();
if(outputJson == null){
// create a root of the JSON
outputJson = factory.objectNode();
outputJson.put(nodeOfQueue.target, createJsonRecursively(outputJson));
}else if (jsonRoot.get(nodeOfQueue.source).isObject()){
// create an object to conatin other values/object
ObjectNode objectNode = factory.objectNode();
objectNode.put(nodeOfQueue.target,createJsonRecursively(outputJson));
outputJson.putAll(objectNode);
}else if(jsonRoot.get(nodeOfQueue.source).isArray()){
// create an array node and call for to create value it contains
ArrayNode arrayNode = factory.arrayNode();
int size = jsonRoot.get(nodeOfQueue.source).size();
for(int index = 0 ; index < size ; index++){
arrayNode.add(jsonRoot.get(nodeOfQueue.source).get(index));
}
outputJson.put(nodeOfQueue.target,arrayNode);
}else if(nodeOfQueue.isEnd){
// create leaf node
outputJson.put(nodeOfQueue.target, jsonRoot.get(nodeOfQueue.source));
return outputJson;
}
return outputJson;
}
Related
Code: Search word in Trie
Implement the function SearchWord for the Trie class.
For a Trie, write the function for searching a word. Return true if the word is found successfully, otherwise return false.
Note: main function is given for your reference which we are using internally to test the code.
class TrieNode{
char data;
boolean isTerminating;
TrieNode children[];
int childCount;
public TrieNode(char data) {
this.data = data;
isTerminating = false;
children = new TrieNode[26];
childCount = 0;
}
}
public class Trie {
private TrieNode root;
public int count;
public Trie() {
root = new TrieNode('\0');
count = 0;
}
private boolean add(TrieNode root, String word){
if(word.length() == 0){
if (!root.isTerminating) {
root.isTerminating = true;
return true;
} else {
return false;
}
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if(child == null){
child = new TrieNode(word.charAt(0));
root.children[childIndex] = child;
root.childCount++;
}
return add(child, word.substring(1));
}
public void add(String word){
if (add(root, word)) {
this.count++;
}
}
public boolean search(String word){
// add your code here
return search(root,word);
}
private boolean search(TrieNode root, String word){
if(word.length()==0){
return true;
}
int childIndex = word.charAt(0) -'a';
TrieNode child = root.children[childIndex];
if(child==null){
return false;
}
return search(child, word.substring(1));
}
}
//Main Function
code
import java.io.*;
public class Runner {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException{
Trie t = new Trie();
String[] string = br.readLine().split("\\s");
int choice = Integer.parseInt(string[0]);
String word = "Null";
if (string.length!=1)
{
word = string[1];
}
while(choice != -1) {
switch(choice) {
case 1 : // insert
t.add(word);
break;
case 2 : // search
System.out.println(t.search(word));
break;
default :
return;
}
string = br.readLine().split("\\s");
choice = Integer.parseInt(string[0]);
if (string.length!=1)
{
word = string[1];
}
}
}
}
You need to make use of the isTerminating information. In search, change:
if(word.length()==0){
return true;
}
To:
if(word.length()==0){
return root.isTerminating;
}
I'm trying to write a code that split a spaceless string into meaningful words but when I give sentence like "arealways" it returns ['a', 'real', 'ways'] and what I want is ['are', 'always'] and my dictionary contains all this words. How can I can write a code that keep backtracking till find the best matching?
the code that returns 'a', 'real', 'ways':
splitter.java:
public class splitter {
HashMap<String, String> map = new HashMap<>();
Trie dict;
public splitter(Trie t) {
dict = t;
}
public String split(String test) {
if (dict.contains(test)) {
return (test);
} else if (map.containsKey(test)) {
return (map.get(test));
} else {
for (int i = 0; i < test.length(); i++) {
String pre = test.substring(0, i);
if (dict.contains(pre)) {
String end = test.substring(i);
String fixedEnd = split(end);
if(fixedEnd != null){
map.put(test, pre + " " + fixedEnd);
return pre + " " + fixedEnd;
}else {
}
}
}
}
map.put(test,null);
return null;
}
}
Trie.java:
public class Trie {
public static class TrieNode {
private HashMap<Character, TrieNode> charMap = new HashMap<>();
public char c;
public boolean endOWord;
public void insert(String s){
}
public boolean contains(String s){
return true;
}
}
public TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String s){
TrieNode p = root;
for(char c : s.toCharArray()) {
if(! p.charMap.containsKey(c)) {
TrieNode node = new TrieNode();
node.c = c;
p.charMap.put(c, node);
}
p = p.charMap.get(c);
}
p.endOWord = true;
}
public boolean contains(String s){
TrieNode p = root;
for(char c : s.toCharArray()) {
if(!p.charMap.containsKey(c)) {
return false;
}
p = p.charMap.get(c);
}
return p.endOWord;
}
public void insertDictionary(String filename) throws FileNotFoundException{
File file = new File(filename);
Scanner sc = new Scanner(file);
while(sc.hasNextLine())
insert(sc.nextLine());
}
public void insertDictionary(File file) throws FileNotFoundException{
Scanner sc = new Scanner(file);
while(sc.hasNextLine())
insert(sc.nextLine());
}
}
WordSplitter class:
public class WordSplitter {
public static void main(String[] args) throws FileNotFoundException {
String test = "arealways";
String myFile = "/Users/abc/Desktop/dictionary.txt";
Trie dict = new Trie();
dict.insertDictionary(myFile);
splitter sp = new splitter(dict);
test = sp.split(test);
if(test != null)
System.out.println(test);
else
System.out.println("No Splitting Found.");
}
}
Using the OP's split method and the implementation of Trie found in The Trie Data Structure in Java Baeldung's article, I was able to get the following results:
realways=real ways
arealways=a real ways
However, if I remove the word "real" or "a" from the dictionary, I get the following results:
realways=null
arealways=are always
Here's the entire code I used to get these results:
public class Splitter {
private static Map<String, String> map = new HashMap<>();
private Trie dict;
public Splitter(Trie t) {
dict = t;
}
/**
* #param args
*/
public static void main(String[] args) {
List<String> words = List.of("a", "always", "are", "area", "r", "way", "ways"); // The order of these words does not seem to impact the final result
String test = "arealways";
Trie t = new Trie();
for (String word : words) {
t.insert(word);
}
System.out.println(t);
Splitter splitter = new Splitter(t);
splitter.split(test);
map.entrySet().forEach(System.out::println);
}
public String split(String test) {
if (dict.find(test)) {
return (test);
} else if (map.containsKey(test)) {
return (map.get(test));
} else {
for (int i = 0; i < test.length(); i++) {
String pre = test.substring(0, i);
if (dict.find(pre)) {
String end = test.substring(i);
String fixedEnd = split(end);
if (fixedEnd != null) {
map.put(test, pre + " " + fixedEnd);
return pre + " " + fixedEnd;
} else {
}
}
}
}
map.put(test, null);
return null;
}
public static class Trie {
private TrieNode root = new TrieNode();
public boolean find(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.getChildren().get(ch);
if (node == null) {
return false;
}
current = node;
}
return current.isEndOfWord();
}
public void insert(String word) {
TrieNode current = root;
for (char l : word.toCharArray()) {
current = current.getChildren().computeIfAbsent(l, c -> new TrieNode());
}
current.setEndOfWord(true);
}
#Override
public String toString() {
return toString(root);
}
/**
* #param root2
* #return
*/
private String toString(TrieNode node) {
return node.toString();
}
public static class TrieNode {
private Map<Character, TrieNode> children = new HashMap<>() ;
private String contents;
private boolean endOfWord;
public Map<Character, TrieNode> getChildren() {
return children;
}
public void setEndOfWord(boolean endOfWord) {
this.endOfWord = endOfWord;
}
public boolean isEndOfWord() {
return endOfWord;
}
#Override
public String toString() {
StringBuilder sbuff = new StringBuilder();
if (isLeaf()) {
return sbuff.toString();
}
children.entrySet().forEach(entry -> {
sbuff.append(entry.getKey() + "\n");
});
sbuff.append(" ");
return children.toString();
}
private boolean isLeaf() {
return children.isEmpty();
}
}
public void delete(String word) {
delete(root, word, 0);
}
private boolean delete(TrieNode current, String word, int index) {
if (index == word.length()) {
if (!current.isEndOfWord()) {
return false;
}
current.setEndOfWord(false);
return current.getChildren().isEmpty();
}
char ch = word.charAt(index);
TrieNode node = current.getChildren().get(ch);
if (node == null) {
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1) && !node.isEndOfWord();
if (shouldDeleteCurrentNode) {
current.getChildren().remove(ch);
return current.getChildren().isEmpty();
}
return false;
}
}
}
I improved the original code by adding a toString() method to the Trie and TrieNode. Now, when I print out the Trie object "t", I get the following result:
{a={r={e={a=}}, l={w={a={y={s=}}}}}, w={a={y={s=}}}}
My conclusion is that the OP's TrieNode implementation is incorrect. The way the Trie is built, given the inputted string value, the behavior described by the OP seems to be correct.
I've been struggling with implementing a Binary Search Tree with the Iterator method. I've been checking out this algorithm out on WikiPedia:
def search_recursively(key, node):
if node is None or node.key == key:
return node
if key < node.key:
return search_recursively(key, node.left)
# key > node.key
return search_recursively(key, node.right)
I translated it to Java:
public Iterator<T> iterator()
{
return new Iterator<T>()
{
private int count = 0;
#Override
public boolean hasNext()
{
return count++ < size;
}
#Override
public T next()
{
return search(root, root.word);
}
public T search(BST root, T word)
{
if (root == null || root.word.compareTo(word) == 0)
{
return root.word;
}
if (root.word.compareTo(word) < 0)
{
return search(root.left, word);
}
return search(root.right, word);
}
};
When trying to run the program I only get the root element of the BST:
MyWordSet bst = new MyWordSet();
T bst = new T("one");
T bst = new T("two");
T bst = new T("three");
T bst = new T("four");
T bst = new T("five");
T bst = new T("six");
bst.add(w1);
bst.add(w2);
bst.add(w3);
bst.add(w4);
bst.add(w5);
bst.add(w6);
Iterator<T> it = bst.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
So the output is:
one
one
one
one
one
one
So why does this method inside my Iterator not work for me to get to the whole tree? I really can't figure out what is wrong here and why it only prints out one when it should go down the tree.
You simply do not update the current_node.
The equivalent of current_node = node is missing.
Well, after having changed the code, here revised answer:
import java.util.Iterator;
import java.util.Stack;
/**
*
* #author jk
*/
public class BSTIterator<T> implements Iterator<T> {
public static final class BST<T> {
private BST<T> left;
private BST<T> right;
private T word;
private BST(T word) {
this.word = word;
}
}
private final Stack<BST<T>> stackBST = new Stack<>();
public BSTIterator(final BST<T> root) {
// push all most left entries of the tree to the stack
BST<T> currBST = root;
while (currBST != null) {
stackBST.push(currBST);
currBST = currBST.left;
}
}
#Override
public boolean hasNext() {
return !stackBST.isEmpty();
}
#Override
public T next() {
BST<T> currBST = stackBST.pop();
// check if we are on the most right entry
final boolean notMostRightEntry = currBST.right != null;
if (notMostRightEntry) {
// take next right entry
BST<T> nextBST = currBST.right;
while (nextBST != null) {
// push this next right entry on the stack
stackBST.push(nextBST);
nextBST = nextBST.left;
}
}
return currBST.word;
}
public static void main(String[] args) {
BST<Integer> root = new BST<>(20);
root.left = new BST<>(5);
root.right = new BST<>(30);
root.left.right = new BST<>(10);
root.right.left = new BST<>(25);
root.right.right = new BST<>(40);
root.right.left = new BST<>(35);
root.right.left.left = new BST<>(32);
for (Iterator<Integer> bstIt = new BSTIterator<>(root); bstIt.hasNext();) {
System.out.println("val: " + bstIt.next());
}
}
}
I have recently been working on developing a class to see the given undirected graph has a Hamiltonian cycle. I found out this interesting article http://www.geeksforgeeks.org/backtracking-set-7-hamiltonian-cycle/.I've developed my code accordingly. But the problem is the algorithms fails to return a hamiltoninan cycle.
Graph.java:
package graph;
public class Graph {
private static Map<String, Vertex> vertices = new HashMap<String, Vertex> ();
public static Map<String, LinkedList<Edges>> vertexs = new HashMap<String, LinkedList<Edges>>();
private static Vector<Vertex> verticesID =new Vector<Vertex>();
private static Vector<String> verticesIDString =new Vector<String>();
public Graph(String fileName) {
// TODO Auto-generated constructor stub
this.LoadGraph(fileName);
}
public int addVertex(String ID){
if (vertices.containsKey(ID))
return -1;
Vertex vertex=new Vertex(ID);
vertices.put(ID, vertex);
LinkedList<Edges> node =new LinkedList<Edges>();
vertexs.put(ID, node);
return 1;
}
public int addEdge(String from, String to, double weight){
//check whether the vertices exist or not
if (vertices.containsKey(from) && vertices.containsKey(to)){
vertices.get(from).addEdge(to, weight);
Edges newEdge = new Edges(from,to,weight);
if(vertexs.get(from) == null)
{
vertexs.put(from, new LinkedList<Edges>());
}
vertexs.get(from).add(newEdge);
return 1;
}
else{
System.err.println ("'From' vertex and/or 'to' vertex dosen't exist! ");
return -1;
}
}
private int LoadGraph(String fileName) {
File f;
BufferedReader in;
try {
f = new File(fileName);
in = new BufferedReader(new FileReader(f));
String delim = "[ ]+";
//String delim = "\t";
String from; String to;double weight;
int cnt = 0;
String line = in.readLine();
//System.out.println(line);
while (line != null) {
//String[] tokens=line.split(delim);
String[] tokens=line.split(delim,-1);
//if there're less than three entries (from,to, weight) then report err
if (tokens.length<3){
System.err.println ("Invalid line format. Line should be formated as: from to weight");
in.close();
return -1;
}
from=tokens[0];
to=tokens[1];
weight=Double.parseDouble(tokens[2]);
//first create the "from" vertex if it's not already created
this.addVertex(from);
//Then create the "to" vertex if it's not already created
this.addVertex(to);
//now associate the "from" vertex with "to" vertex using "weight"
this.addEdge(from, to,weight);
//do the association the other way around, i.e. force graph to be undirected.
this.addEdge(to, from,weight);
//if the "from" vertex is a new one, add it to the key vector
if (!verticesIDString.contains(from)) {
verticesIDString.add(from);
verticesID.add(new Vertex(from));
}
//if the "to" vertex is a new one, add it to the key vector
if (!verticesIDString.contains(to)) {
verticesIDString.add(to);
verticesID.add(new Vertex(to));
}
cnt++;
line = in.readLine();
//System.out.println(line);
}
in.close();
System.out.println(vertices.size());
System.out.println("Successfully added "+cnt+" associations");
return cnt;
} catch (IOException exc) {
System.err.println(exc.toString());
return -1;
}
}
public static ArrayList<Edges> getChildNodes(String node)
{
LinkedList<Edges> neighboursList;
Set<String> keys = vertexs.keySet();
for (String key : keys)
{
if (key.equals(node))
{
neighboursList = vertexs.get(key);
return new ArrayList<Edges>(neighboursList);
}
}
return new ArrayList<Edges>();
}
public Vertex getVertex(String ID){
return vertices.get(ID);
}
public static int getVerticesCount(){
return verticesID.size();
}
public static Vertex getVertexIdByIndex(int idx){
return verticesID.elementAt(idx);
}
public Vector<String> BFS(String start){
//Vector<String> tour = new Vector<String>();
Vector<String> visited = new Vector<String>();
LinkedList<String> queue = new LinkedList<String>();
visited.add(start);
queue.add(start);
while(queue.size() != 0){
String s = queue.poll();
//tour.add(s);
ArrayList<Edges> al = getChildNodes(s);
Iterator<Edges> i = al.listIterator();
while (i.hasNext())
{
String n = i.next().toVertex();
if (!visited.contains(n))
{
visited.add(n);
queue.add(n);
}
}
}
return visited;
}
}
Hamiltoninan.java:
package graph;
public class HamiltonianCycle {
public Vector<String> findHamiltonianCycle(Graph g,String start){
Vector<String> allVertex = g.BFS(start); //this will help us with all the vertices in the graph
Vector<String> path = new Vector<String>(); // To store the hamiltonian path
/*Initialize the path with null at first*/
for(int i=0;i < allVertex.size();i++){
path.add(null);
}
path.add(start); // add the start as the first vertex of the hamiltonian path
/**
*now the recursive functions
*cycle problem
**/
if (hamCycleUtil(g, path,allVertex) == false)
{
System.out.println("\nSolution does not exist");
return null;
}
return path;
}
//The utility function tha recursively finds the hamiltonian cycle
private boolean hamCycleUtil(Graph g, Vector<String> path,Vector<String> vers) {
// TODO Auto-generated method stub
if(path.size() == Graph.getVerticesCount()){
String s1 = path.lastElement();
ArrayList<Edges> LastNodeEdges = Graph.getChildNodes(s1);
for(Edges Node : LastNodeEdges){
if(Node.toVertex().equals(path.firstElement())){
System.out.println(path);
return true;
}
}
return false;
}
for(int i=1;i<vers.size();i++){
if(isSafe(vers.elementAt(i),g,path)){
path.add(vers.elementAt(i));
if(hamCycleUtil(g, path, vers) == true){
return true;
}
}
}
return false;
}
private boolean isSafe(String elementAt, Graph g, Vector<String> path) {
// TODO Auto-generated method stub
if(path.contains(elementAt)){
return false;
}
return true;
}
}
Can somebody point me out where the problem is and how can i solve the problem.
thanks,
Karthi.
Hey guys I am trying to read from a text file and store each name into a linked list node. When I read in the text file it reads the line, which is a name. I am trying to store each name into a linked list node. When I call the insertBack method and print it out, it shows that there is nothing in the nodes. Could anybody point me in the right direction, it would be much appreciated?
Here is the fileIn class:
import java.util.Scanner;
import java.io.*;
public class fileIn {
String fname;
public fileIn() {
getFileName();
readFileContents();
}
public void readFileContents()
{
boolean looping;
DataInputStream in;
String line;
int j, len;
char ch;
/* Read input from file and process. */
try {
in = new DataInputStream(new FileInputStream(fname));
LinkedList l = new LinkedList();
looping = true;
while(looping) {
/* Get a line of input from the file. */
if (null == (line = in.readLine())) {
looping = false;
/* Close and free up system resource. */
in.close();
}
else {
System.out.println("line = "+line);
j = 0;
len = line.length();
for(j=0;j<len;j++){
System.out.println("line["+j+"] = "+line.charAt(j));
}
}
l.insertBack(line);
} /* End while. */
} /* End try. */
catch(IOException e) {
System.out.println("Error " + e);
} /* End catch. */
}
public void getFileName()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter file name please.");
fname = in.nextLine();
System.out.println("You entered "+fname);
}
}
This is the LinkedListNode class:
public class LinkedListNode
{
private String data;
private LinkedListNode next;
public LinkedListNode(String data)
{
this.data = data;
this.next = null;
}
public String getData()
{
return data;
}
public LinkedListNode getNext()
{
return next;
}
public void setNext(LinkedListNode n)
{
next = n;
}
}
And finally the LinkedList class that has the main method:
import java.util.Scanner;
public class LinkedList {
public LinkedListNode head;
public static void main(String[] args) {
fileIn f = new fileIn();
LinkedList l = new LinkedList();
System.out.println(l.showList());
}
public LinkedList() {
this.head = null;
}
public void insertBack(String data){
if(head == null){
head = new LinkedListNode(data);
}else{
LinkedListNode newNode = new LinkedListNode(data);
LinkedListNode current = head;
while(current.getNext() != null){
current = current.getNext();
}
current.setNext(newNode);
}
}
public String showList(){
int i = 0;
String retStr = "List nodes:\n";
LinkedListNode current = head;
while(current != null){
i++;
retStr += "Node " + i + ": " + current.getData() + "\n";
current = current.getNext();
}
return retStr;
}
}
The problem is that you create the LinkedList in your fileIn.
But then you do not export it:
fileIn f = new fileIn();
LinkedList l = new LinkedList();
What you need is something like this:
fileIn f = new fileIn();
LinkedList l = f.readFileContents(String filename, new LinkedList());
Change the method to use the LinkedList you created and then populate it. So the fileIn class might look like something like this:
public class fileIn {
...
public void readFileContents(String fileName, LinkedList) {
// fill linked list
}
...
}