Scanner class problems
hi, i want to read in entire lines of from the user
and have the loop terminate when user hits enter on a blank line
the loop never ends! please help. my this is just a test class for
the rest of a program i am just abo0ut finished
this is what i have for the loop:
System.out.println("Enter sentences, after each sentence hit enter\n" +
"hit enter on an empty line to stop :\n");
System.out.println("beginning of iteration\n");
aString = sc.nextLine();
System.out.println("end of iteration\n");
}while(sc.nextLine() != null);
null means, nothing... 0
How about enter? that generates a newline right?values 0A in hex....
Try to print what
prints, since that comparison always true, then sc.nextLine() should have captured some text from console...
while(sc.nextLine() != null);
and i guess, that will prints "end of iteration"
or another flag that could negate the comparison,
eg. if(sc.nextLine().equals("x") then terminate....
yes! thank you. i though that null == " " for some reason.
You got a collision with null and empty string there.
String aString = null;//never creates sring object
String aString = " ";//memory IS allocated for string object.
i guess thats the difference right?
Yeah, the null is just a null pointer, i.e. a pointer which doesn't point to any object in memory. With the second one the string " " is stored in memory and the String object aString contains a pointer to that string.
When you test the user input first use the trim() method on the string. That is:
You can still test null too here. It's better too.