Sunday, March 24, 2013

Java / Scanner class. Simple example of Sanner.in

How to read something from console?
Java provides Scanner class to read from input.

Example:

import java.util.Scanner;

public class MyScanner 
{
 public static void main(String[] args) 
 {
  Scanner in = new Scanner( System.in );
  boolean isExit = false;
  
  while( !isExit )
  {
   System.out.println( "Write something to me" );
   String line = in.nextLine();
   
   System.out.println( "Your text: " + line );
   
   if( line.equals("exit") )
   {
    isExit = true;
    System.out.println( "You have choosen exit. Bye bye." );
   }
  }
  in.close();
 }
}


In this loop you can read everything you want from console and your text will be displayed in line #15..
If you type "exit" the program will terminate.

More about Scanner class you can read from official documentation here. (Java 1.6)

No comments: