Hi Guys,

So I'm trying to fix a small problem with my code. It does everything correctly but when reading from the file I want to not count the space between words. For instance if the line is Hello world the output should be:
11: Hello world
but instead it prints
12: Hello world

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class MarshallTracie6<T> extends AbstractCollection<T> {
	/* Creates a new LinkedList called list. */
	LinkedList<T> list = new LinkedList<T>();

	/* add method calls on LinkedList's add method and overrides it. */
	public boolean add(T value) {
		list.add(value);
		return true;
	}

	/* Constructor for MarshallTracie6 */
	public MarshallTracie6() {

	}

	/* Creates a new ListIterator */
	public ListIterator<T> iterator() {
		ListIterator<T> iterator = new ListIterator<T>(list);
		return iterator;
	}

	/* The size method, call on the getSize method and returns the size. */
	public int size() {
		return list.getSize();

	}

	/* Creates a String printCollection and returns it. */
	public String toString() {
		String printer = "";
		ListIterator<T> myIterator = iterator();

		while (myIterator.hasNext()) {
			String currentLine = myIterator.next() + "";
			printer += currentLine.length() + ": " + currentLine + "\n";
		}
		return printer;
	}

	public static void main(String[] args) {
		/* Creates a new instance or MarshallTracie6 called myCollection */
		MarshallTracie6<String> myCollection = new MarshallTracie6<String>();

		if (args.length == 1) {
			try {
				// open the file for reading 
				File file = new File(args[0]);
				Scanner scan = new Scanner(file);

				 //Reads the lines off the file 
				while (scan.hasNextLine()) {
					if (scan.hasNextLine()) {
						String line = scan.nextLine();
						myCollection.add(line);
					}

				}
				// Prints out the collection.
				System.out.println ("The Collection :");
				System.out.println(myCollection);

				// Catches and handles the FileNotFoundException 
			} catch (FileNotFoundException e) {
				System.out.println("Error:  File does not exist!");
				System.exit(0);
			}
		} else {
			System.out.println("Expected one file name as a parameter,found : "
					+ args.length);
		}
		
		// myCollection.add("Foo");
		// myCollection.add("Bar");
		// myCollection.add("What?");
		// System.out.print(myCollection);

	}
}

/* The Generic node class */
class Node<T> {
	/*
	 * two fields, the first to store the item itself, the second is a pointer
	 * to the next node in the linked list. If there is no next node, the
	 * pointer is null.
	 */
	private T item;
	private Node<T> nextNode;

	/*
	 * constructor:
	 * 
	 * @param value, the value for the node
	 * 
	 * @param next, the next node in the linked list
	 */
	public Node(T value, Node<T> next) {
		item = value;
		nextNode = next;
	}

	/* Accessor methods */
	public T getValue() {
		return item;
	}

	public Node<T> getNext() {
		return nextNode;
	}

	/* mutator methods */
	public void setNext(Node<T> newNext) {
		nextNode = newNext;
	}

	public void setValue(T value) {
		item = value;
	}
}

/*
 * The LinkedList class;
 */
class LinkedList<T> {
	/*
	 * only need to store a single pointer to the node at the head of the list.
	 * The pointer is null if the list is empty. Also record the size of the
	 * list.
	 */
	protected Node<T> head;
	/* invariant: size is the number of nodes in the list pointed to by head */
	protected int size;

	// Method to return the size
	public int size() {
		return size;
	}

	/* no-arguments default constructor creates an empty list */
	public LinkedList() {
		head = null; // start with an empty list
	}

	/*
	 * @param value to add to the end of the list
	 */
	public void add(T value) {
		head = addAtEnd(head, value);
			size++;
	}

	// Returns the size
	public int getSize() {
		return size;
	}

	/*
	 * @param node of the list to which the value should be added
	 * 
	 * @param value to add to the end of the list
	 */
	private Node<T> addAtEnd(Node<T> node, T value) {
		if (node == null) { // special case
			return new Node<T>(value, null);
		} else if (node.getNext() == null) { // other special case
			node.setNext(new Node<T>(value, null));
		} else {
			addAtEnd(node.getNext(), value);
		}
		return node;
	}

	/*
	 * @param position of item to be removed
	 * 
	 * @throws BadItemCountException if this is not a valid position position is
	 * 1-based, so position = 1 removes the head
	 */
	public void remove(int position) {
		if (position == 1) {
			head = head.getNext();
		} else {
			Node<T> node = head;
			for (int i = 2; i < position; i++) {
				node = node.getNext();
			}
			// set this node's "next" pointer to refer to the
			// node that is after the next
			node.setNext(node.getNext().getNext());
		}
	}

	/*
	 * convert the list to a printable string
	 * 
	 * @return a string representing the stack
	 */
	public String toString() {
		return toString(head);
	}

	private String toString(Node<T> node) {
		if (node == null) {
			return "";
		} else {
			return node.getValue() + "\n" + toString(node.getNext());
		}
	}
}

class ListIterator<T> extends LinkedList<T> implements Iterator<T> {
	/*
	 * a single field to store the first node, or null.
	 */
	private Node<T> nextNode;

	public ListIterator(LinkedList<T> list) {
		nextNode = list.head; // head is protected, so accessible to subclass
	}

	/*
	 * can at least one more value that can be accessed with this iterator?
	 * 
	 * @return whether there is another node
	 */
	public boolean hasNext() {
		return (nextNode != null);
	}

	/*
	 * @return the next value
	 * 
	 * @throws NoSuchElementException if there is no such value
	 */
	public T next() {
		if (hasNext()) {
			T value = nextNode.getValue();
			nextNode = nextNode.getNext();
			return value;
		} else {
			throw new NoSuchElementException("NodeIterator");
		}
	}

	/*
	 * @throws UnsupportedOperationException, meaning remove is not supported
	 */
	public void remove() {
		throw new UnsupportedOperationException("NodeIterator");
	}

}

Dani AI

Generated

— the symptom (shows 12 when you expect 11) usually comes from an extra, invisible character in the String rather than a bug in the linked‑list. was right to point toward the Character helpers; here are quick, practical steps to find and fix the problem.

To diagnose: print each character code for the problematic line to see if there is a carriage return, BOM, or other nonprinting character:

for (int i = 0; i < line.length(); i++) {
    System.out.printf("%d: 0x%04X '%c'%n", i, (int) line.charAt(i), line.charAt(i));
}

If you see 0x000D (CR) or 0xFEFF (BOM) or other unexpected code points, remove them explicitly.

Ways to compute the length while ignoring spaces/whitespace:

  • Ignore ASCII space only:

    int count = line.replace(" ", "").length();
  • Ignore all whitespace (spaces, tabs, NBSP, etc.):

    int count = line.replaceAll("\\s+", "").length();
  • Or count manually with Character methods (clear and explicit):

    int nonWhitespaceCount(String s) {
      int c = 0;
      for (int i = 0; i < s.length(); i++) {
          if (!Character.isWhitespace(s.charAt(i))) c++;
      }
      return c;
    }

If you find a BOM at the start, strip it with:

if (!s.isEmpty() && s.charAt(0) == '\uFEFF') s = s.substring(1);

Small cautions: replaceAll("\\s+") uses regex and removes every whitespace character (including tabs); replace(" ", "") only removes literal spaces. Use the approach that matches the requirement (only ignore spaces between words, or ignore all whitespace). Finally, change the place where you build the printed length (in your toString) to use one of the counting methods above rather than currentLine.length().

Recommended Answers

All 2 Replies

That was helpful. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.