Inserting text file input into a linked list - java

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
}
...
}

Related

(JAVA) How do I Remove the First Element in a Circular Doubly Linked List?

I've managed to make the doubly linked list into a circular one, I'm just having trouble making a method to remove the first element. I've tried looking at examples for single linked lists but I can't seem to modify it to fit my code. Any help would be greatly appreciated.
Linkedlist Class
package LinkedListS;
public class LinkedList {
private Node first;
private Node end;
LinkedList()
{
first = end = null;
}
public void addAtStart(int x){
Node temp = new Node(x);
if(first == null)
{
first = end = temp;
}
else
{
end.setNext(temp);
temp.setNext(first);
first = temp;
}
}
public void printFromStart()
{
Node temp = first;
do {
System.out.println(temp.getData());
temp = temp.getNext();
end.setNext(null);
} while (temp != null);
}
public void searchFromStart(int elementToBeSearched)
{
Node temp = first;
while(temp != null)
{
if (temp.getData() == elementToBeSearched)
{
System.out.println("Found " + elementToBeSearched);
return;
}
temp = temp.getNext();
}
System.out.println("Didn't find " + elementToBeSearched);
}
public void removeFirstElement(){
}
Driver Class:
enter code here
public class LinkedListMain {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
System.out.println("Going to add elements At Start");
ll.addAtStart(5);
ll.addAtStart(7);
ll.addAtStart(9);
ll.addAtStart(10);
System.out.println("Print the doubly linked list elements");
ll.printFromStart();
System.out.println("Search the following elements");
ll.searchFromStart(7);
ll.searchFromStart(1289);
ll.removeFirstElement();
ll.printFromStart();
}
}
Node Class:
package LinkedListS;
public class Node {
private int data;
private Node next;
private Node prev;
// Constructor to intialize/fill data
public Node(int data)
{
this.data = data;
}
// set the address of next node
public void setNext(Node temp)
{
this.next = temp;
}
// get the address of next node
public Node getNext()
{
return this.next;
}
public Node getPrev()
{
return this.prev;
}
public void setPrev(Node temp)
{
this.prev = temp;
}
// to get data of current node
public int getData()
{
return this.data;
}
}
For the removeFirstElement method I've tried these solutions with no avail:
Attempt #1
Node temp = first;
temp = null;
Attempt #2
Node temp = first;
if(first != null){
if(temp.getNext() == first){
first = null;
}
} else {
first = end;
end = first.getNext();
}
Attempt #3
Node temp = first;
if (first == null) {
System.out.println("There is no first element to remove");
} else
temp = first;
System.out.println(temp);
Attempt #4
Node temp = first;
end = null;
if(first != null){
if(temp.getNext() == temp){
first = null;
}
} else {
end = first;
first = first.getNext();
}
After scanning a few other methods that is what I found that works:
public void removeFirstElement(){
if (first != null){
first = first.getNext();
} else {
System.out.println("There is nothing to be removed");
}
}

How do you reference a list previously created in another method and search through it?

So I have to read a file name that is read from the terminal.The user has to be able to search for a word and then look through a list of words that have those same characters. I plan to use the goToNext and getCurrent to read and scan through the list. But i dont know how to scan through the list i previously made in the method loadDataBase
public class GameLL <T>{
private class ListNode{
T data;
ListNode link;
public ListNode(T aData, ListNode aLink){
data = aData;
link = aLink;
}
}
public static GameLL<String> list = new GameLL<String>();
private ListNode head;
private ListNode current;
private ListNode previous;
public Object getCurrent;
public GameLL() {
head = current = previous = null;
}
public void add(T aData){
ListNode newNode = new ListNode(aData, null);
if(head == null){
head = current = newNode;
return;
}
ListNode temp = head;
while (temp.link != null){
temp = temp.link;
}
temp.link = newNode;
}
public void print(){
ListNode temp = head;
while(temp != null){
System.out.println(temp.data);
temp = temp.link;
}
}
public T getCurrent(){
if (current == null){
return null;
}
return current.data;
}
public void reset(){
current = head;
previous = null;
}
public void gotoNext(){
if(current == null){
return;
}
previous = current;
current = current.link;
}
}
Below is my methods that will be called in the main method. Im struggling here! Im not crazy at coding so my code might look like dog poop sorry
package Homework02.src;
import java.util.Scanner;
import java.io.*;
public class OtherMethods {
public static void options() throws IOException{
while (loopStatus.loopRunning){
System.out.println("Enter 1 to load the video game database");
System.out.println("Enter 2 to search the database");
System.out.println("Enter 3 to print current results");
System.out.println("Enter 4 to print current results to file");
System.out.println("Enter 0 to quit");
otherMethods.userOptionCheck();
}
}
public static class LoopStatus{
public static boolean loopRunning;
}
public static class UserInput{
public static int menuChoice;
public static String filePath;
}
public static class Counter{
public static int numOfLines = 0;
}
private static class Game{
private static String contentOnLine;
private static String name;
private static String console;
}
public static void userOptionCheck() throws IOException {
Scanner keyboard = new Scanner(System.in);
UserInput.menuChoice = keyboard.nextInt();
switch (UserInput.menuChoice) {
case 1:
otherMethods.loadDataBase();
System.out.println("\nDone Loading Data Base\n");
break;
case 2:
otherMethods.searchDataBase();
break;
case 3:
// TODO call method to print out the current results
break;
case 4:
// TODO call method to print current results to file
break;
case 0:
loopStatus.loopRunning = false;
break;
default:
System.out.println("You choose an invalid option... Please choose one of the five options listed.\n");
break;
}
}
public static void loadDataBase() throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please specify either the relative file path or the absolute filepath: ");
UserInput.filePath = keyboard.nextLine();
GameLL<String> list = new GameLL<String>();
try {
File inputList = new File(UserInput.filePath);
Scanner fileReader = new Scanner(new FileInputStream(inputList));
while (fileReader.hasNextLine()) {
counter.numOfLines++;
Game.contentOnLine = fileReader.nextLine();
list.add(Game.contentOnLine);
}
fileReader.close();
} catch (FileNotFoundException fnf) {
System.out.println("\nhey i cant find the file\n");
fnf.printStackTrace();
}catch (Exception e) {
System.out.println("\nProgram is now exiting\n");
e.printStackTrace();
}
}
public static void searchDataBase(){
GameLL<String> searchResults = new GameLL<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the name of game or * for all names");
Game.name = keyboard.nextLine().toLowerCase();
System.out.println("Enter the name of the console or * for all consoles");
Game.console = keyboard.nextLine().toLowerCase();
int found = 0;
System.out.println();
for (int i = 0; i < counter.numOfLines;i++){
//THIS DOESNT WORK BECAUSE I CANT REFERENCE MY PREVIOUS "list" IN MY OTHER METHOD
if(list.getCurrent.toLowerCase().contains(Game.name)){
System.out.println("FOUND A WORD THAT CONTAINS PART OF THE NAME");
searchResults.add(list.getCurrent);
found++;
}
else{
System.out.println("Could not find a word on this line");
}
list.gotoNext;
searchResults.gotoNext();
}
System.out.println(found);
}
}
Here is currently my main method!
import Homework02.src.otherMethods.loopStatus;
import java.io.*;
public class FrontEndGameSearch {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the video game database\n");
loopStatus.loopRunning = true;
while (loopStatus.loopRunning){
otherMethods.options();
}
System.out.println("YOU ARE OUTSIDE THE LOOP");
}
}

LinkedList Deep copy java

I was trying to do the deep copy of my linked list known as DictionaryNode which I did but i was not able to display it's content in display method as it is always null. why DictinaryNode temp is always null ? and if i try to assign temp = head work but with temp = copy doesn't.
public class ListOfNodes {
public class DictionaryNode {
protected String word;
private int level;
private DictionaryNode next;
private int space = 0;
public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
System.out.println(temp.word)
temp = temp.next;
}
}
public DictionaryNode( String word, int level ) {
this.word = word;
this.level = level;
next = null;
}
}
private DictionaryNode head = null;
public DictionaryNode copy = null;
//used to do deep copy
public void Clone() {
DictionaryNode temp = head.next;
while( temp != null ) {
copy = new DictionaryNode( temp.word , temp.level );
copy = copy.next;
temp = temp.next;
}
}
public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
Sytem.out.println(temp.word)
temp = temp.next;
}
}
This program will demonstrate how to do a deep copy on a list. It's more generic than your specific example so hopefully it helps others too.
public class Java_Practice {
private static class LinkedListTest {
private String data;
private LinkedListTest next;
public LinkedListTest(String data) {
super();
this.data = data;
}
public String getData() {
return data;
}
public LinkedListTest getNext() {
return next;
}
public void setNext(LinkedListTest next) {
this.next = next;
}
#Override
public String toString() {
return "LinkedListTest [data=" + data + ", next=" + next + "]";
}
}
// Do a deep copy
private static LinkedListTest copyLlt(LinkedListTest original) {
LinkedListTest copy = new LinkedListTest(original.getData() + " copied");
LinkedListTest nextCopy = original.getNext();
LinkedListTest current = copy;
while (nextCopy != null) {
LinkedListTest newCopy = new LinkedListTest(nextCopy.getData() + " copied");
newCopy.setNext(nextCopy.getNext());
current.setNext(newCopy);
current = newCopy;
nextCopy = newCopy.getNext();
}
return copy;
}
public static void main(String[] args) {
LinkedListTest firstLlt = new LinkedListTest("First");
LinkedListTest secondLlt = new LinkedListTest("Second");
LinkedListTest thirdLlt = new LinkedListTest("Thrid");
firstLlt.setNext(secondLlt);
secondLlt.setNext(thirdLlt);
LinkedListTest copiedLlt = copyLlt(firstLlt);
// Data should say First, Second, Third
System.out.println("Original LinkedListTest: " + firstLlt.toString());
// Data should say First Copied, Second Copied, Third Copied
System.out.println("Copied LinkedListTest: " + copiedLlt.toString());
}
}
In your Clone method you never assign a next field for the copied content. You need to do this to have more than a single connected node in the copy. Furthermore you need to copy the head too. Moreover do must not overwrite copy with anything but the copy of the head:
copy = new DictionaryNode(null, head.level);
DictionaryNode temp = head.next;
DictionaryNode current = copy;
while( temp != null) {
DictionaryNode nn = new DictionaryNode( temp.word , temp.level);
current.next = nn;
current = nn;
temp = temp.next;
}

System printing to a certain index of a linkedList

I am working with java at the moment and I am trying to find out a way to stop printing to the console (for simplicity) after a certain index of a linkedList is reached. Any help explaining this would be much appreciated.
Below is my Node class used to create the list:
protected Integer data;
protected Node link;
public Node(Integer data, Node link) {
this.data = data;
this.link = link;
}
public Node addNodeAfter(Integer element) {
return link = new Node(element, link);
}
public String toString() {
String msg = "";
try {
if (link == null) {
msg = data + " null in tail";
} else {
msg = data + ", " + link.toString();
}
} catch (StackOverflowError e) {
// System.err.println("shit happened here");
}
return msg;
}
public Integer getData() {
return data;
}
public Node getLink() {
return link;
}
Create a method toString(int i) which takes as argument the number of elements which still have to be printed. If the argument is larger than zero and there is a valid link, then recursively call the toString(i - 1) method with i decreased by one:
Code:
public class Node {
public static void main(String[] args) {
Node linkedList = new Node(1, null);
Node node = linkedList;
for (int i = 2; i < 10; ++i)
node = node.addNodeAfter(i);
System.out.println(linkedList.toString(5));
}
public String toString(int i) {
if (i > 0) {
if (link == null)
return data.toString();
else
return data.toString() + " " + link.toString(i - 1);
} else
return "";
}
protected Integer data;
protected Node link;
public Node(Integer data, Node link) {
this.data = data;
this.link = link;
}
public Node addNodeAfter(Integer element) {
return link = new Node(element, link);
}
public Integer getData() {
return data;
}
public Node getLink() {
return link;
}
}
Output
1 2 3 4 5
You will need to extend the LinkedList class and override the toString() method, and then use your subclass.
Something like this:
public class MyLinkedList<E> extends LinkedList<E> {
#Override
public String toString() {
StringBuffer out = new StringBuffer("[");
for (int i=0; i < 3; i++) {
out.append(get(0).toString());
out.append(" ");
}
return out.toString();
}
}
And test it like this:
public class Main {
public static void main(String[] args) {
LinkedList<String> myList = new MyLinkedList<String>();
myList.add("one");
myList.add("two");
myList.add("three");
myList.add("four");
System.out.println(myList);
}
}

Building a tree from string input

I am stuck at the logic as for how to generate a tree when a string input is provided . Such as when i have a input of following form -
(1 (2 (3) (4)) (5 (6) ())
Representing tree will be like so -
1
/ \
2 5
/ \ /\
3 4 6 ()
I can build tree from usual like tree.add(data) and then looking for the new node to be self added by judging if its greater or smaller than parent node . But i am not able to understand how to implement how to store above the above mention string in binary data structure form.
Here's what i have tried so far -
public class BinaryTree {
static Node root;
public static void levelorder(Node<?> n) {
Queue<Node<?>> nodequeue = new LinkedList<Node<?>>();
if (n != null)
nodequeue.add(n);
while (!nodequeue.isEmpty()) {
Node<?> next = nodequeue.remove();
System.out.print(next.data + " ");
if (next.getLeft() != null) {
nodequeue.add(next.getLeft());
}
if (next.getRight() != null) {
nodequeue.add(next.getRight());
}
}
}
private static String[] breakString(String elements) {
int indexOfOpenBracket = elements.indexOf("(");
int indexOfLastBracket = elements.lastIndexOf(")");
String removedPString = elements.substring(indexOfOpenBracket + 1,
indexOfLastBracket);
String[] breakRemovedPString = removedPString.split(" ");
if (breakRemovedPString[1].contains("(")) {
add(breakRemovedPString[0], breakRemovedPString[1], breakRemovedPString[2]);
}
return breakRemovedPString;
}
static void add(String parent, String leftString, String rightString) {
Node<String> nodeToAdd = new Node<String>(parent);
if (root == null) {
root = nodeToAdd;
root.left = new Node<String>(leftString);
root.right = new Node<String>(rightString);
} else {
}
}
public static void main(final String[] args) {
String treeString = "(1 (2) (3))";
breakString(treeString);
levelorder(root);
System.out.println();
}
}
Please suggest some implementation for this problem.
This is a classical parsing problem. The simplest approach is probably recursive descent. Here is a grammar for the tree language:
T -> ( number T T )
| ( number )
| ()
To turn this into a parser, we can go through a formal transformation to LL(1) form and then code. I'll let you read up on that and show what results.
package treereader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
enum Token { LPAREN, RPAREN, NUMBER, EOF, ERROR };
class Scanner {
final Reader in;
final char [] buf = new char[1];
final StringBuilder token = new StringBuilder();
private static final char EOF_MARK = Character.MIN_VALUE;
Scanner(Reader in) {
this.in = in;
read();
}
final void read() {
try {
if (in.read(buf) < 1) {
buf[0] = EOF_MARK;
}
} catch (IOException ex) {
System.err.println("i/o error");
buf[0] = EOF_MARK;
}
}
Token getNext() {
while (Character.isWhitespace(buf[0])) {
read();
}
if (Character.isDigit(buf[0])) {
token.setLength(0);
do {
token.append(buf[0]);
read();
} while (Character.isDigit(buf[0]));
return Token.NUMBER;
}
if (buf[0] == '(') {
read();
return Token.LPAREN;
}
if (buf[0] == ')') {
read();
return Token.RPAREN;
}
if (buf[0] == EOF_MARK) {
return Token.EOF;
}
return Token.ERROR;
}
String getString() {
return token.toString();
}
}
class Node {
public void print(PrintStream out) {
out.print("()");
}
}
class UnaryNode extends Node {
int val;
public UnaryNode(int val) {
this.val = val;
}
#Override
public void print(PrintStream out) {
out.print("(" + val + ")");
}
}
class BinaryNode extends Node {
int val;
Node left, right;
public BinaryNode(int val, Node left, Node right) {
this.val = val;
this.left = left;
this.right = right;
}
#Override
public void print(PrintStream out) {
out.print("(" + val + " ");
left.print(out);
out.print(' ');
right.print(out);
out.print(')');
}
}
class Parser {
final Scanner scanner;
Token lookAhead;
Parser(Reader in) {
scanner = new Scanner(in);
lookAhead = scanner.getNext();
}
void advance() {
lookAhead = scanner.getNext();
}
void match(Token token) throws IOException {
if (lookAhead == token) {
advance();
} else {
throw new IOException("Expected " + token + ", found " + lookAhead);
}
}
Node parse() throws IOException {
Node tree;
match(Token.LPAREN);
if (lookAhead == Token.NUMBER) {
int val = Integer.valueOf(scanner.getString());
advance();
if (lookAhead == Token.LPAREN) {
Node left = parse();
Node right = parse();
tree = new BinaryNode(val, left, right);
} else {
tree = new UnaryNode(val);
}
} else {
tree = new Node();
}
match(Token.RPAREN);
return tree;
}
}
public class TreeReader {
public static void main(String[] args) {
try {
Parser parser = new Parser(new BufferedReader(new FileReader(new File(args[0]))));
Node tree = parser.parse();
tree.print(System.out);
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}

Categories