This program, in theory, should read words from system.in and store
each in a simple list. Using, System.out I know for sure that the
list works fine. It's a problem with my while loop. It never ends.
I've heard things about using == to compare strings instead of != but
nothing works! Any help would be greatly appreciated.
Thank you for your time.
import java.util.Scanner;
public class Parse {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Node head = null;
Node prev = null;
String read = sc.next();
while(sc.next() != null){
Node a = new Node();
a.data = read;
if(head == null){
head = a;
}else{
prev.next = a;
}
prev = a;
read = sc.next();
}
System.out.println("Works"); // Doesn't get to this point
for(Node pointer = head; pointer != null; pointer =
pointer.next){
System.out.println(pointer.data);
}
}
}
class Node{
public Node next;
public String data;
}
Lasse Reichstein Nielsen - 16 Sep 2007 11:06 GMT
> It's a problem with my while loop. It never ends.
...
> import java.util.Scanner;
>
[quoted text clipped - 9 lines]
>
> while(sc.next() != null){
You might mean
while(read != null)
since you are doing two calls to "sc.next" for each loop iteration.
It would be prettier, and probably better working, to do:
while(sc.hasNext()) {
String read = sc.next();
and only have the one call to "sc.next".
Your real problem is that the call "sc.next()" will *never* return
null. It will block if no input is available, and that is where your
program gets stuck.
<URL:http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#next()>
/L

Signature
Lasse Reichstein Nielsen - lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Roedy Green - 16 Sep 2007 14:36 GMT
>import java.util.Scanner;
see http://mindprod.com/jgloss/scanner.html
for an example of use.

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Eric Jablow - 16 Sep 2007 16:06 GMT
> This program, in theory, should read words from system.in and store
> each in a simple list. Using, System.out I know for sure that the
> list works fine. It's a problem with my while loop. It never ends.
> I've heard things about using == to compare strings instead of != but
> nothing works! Any help would be greatly appreciated.
Aside from what the other responses, I have one comment.
If you're doing this for a homework assignment, good. You should do
things by hand at least once. But if this for production code, consider
using java.util.LinkedList<String>:
final Scanner sc = new Scanner(System.in);
final List<String> words = new LinkedList<String>();
while (sc.hasNext()) {
words.add(sc.next());
}
The LinkedListclass does all the work of setting up nodes, using its own
inner class.

Signature
Respectfully,
Eric Jablow