While loop hell.

M

mmoski

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;
}
 
L

Lasse Reichstein Nielsen

mmoski said:
It's a problem with my while loop. It never ends. ....
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){

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
 
E

Eric Jablow

mmoski said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top