• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading from keyboard  RSS feed

 
Stephen Murphy
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to implement a simple game program. I need to read a word from the user, or exit if no word is entered. I am having trouble getting the program to exit.

My code:


[ February 25, 2005: Message edited by: Patrick Murphy ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
readLine() will return null only if the user closes standard input -- i.e., by typing Control-Z on Windows, or Control-D on UNIX. Otherwise if they just hit Enter, readLine() will return a String object whose contents are "" -- i.e., a zero-length String. This is a different thing altogether than null, which is no String.

You want to do something like


[ February 25, 2005: Message edited by: Ernest Friedman-Hill ]
 
nabi bux
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.*;

class Show
{
public static void main(String aff[])
throws Exception
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print("Enter a word to search for : ");
String toFind=" ";
String inLine = br.readLine(); //Reads a word from the keyboard
while((inLine.length() >0)) {
toFind = inLine;
System.out.print("Enter a word to search for : ");

inLine = br.readLine(); //Reads a new word from the keyboard
if(inLine == null)
{
System.exit(0); }}


}}

write down the above code when you type nothing length() function return -1
this cause you loop will end program also thank!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!