• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Reading from keyboard

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
The problems of the world fade way as you eat a piece of pie. This tiny ad has never known problems:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic