Thursday, April 10, 2014

Scanner Class - II


Some other useful Methods of the  Scanner Class :

Method Name
Defination
close()
Closes the scanner.
delimiter()
Returns the Pattern used by current Scanner object.
findInLine(Pattern pattern)
This method returns a String object that satisfies the Pattern.
findInLine(String pattern)
find the next occurrence of the specified pattern
findWithinHorizon(Pattern pattern, int horizon)
Find the next occurrence of the specified pattern.
findWithinHorizon(String pattern, int horizon)
Find the next occurrence of a pattern input ignoring delimiter
hasNext()
Returns true if this scanner has another token.
hasNext(Pattern pattern)
Returns true if the next token matches the specified pattern.
hasNext(String pattern)
Returns true if the next token matches the pattern constructed from the specified string.
hasNextBigDecimal()
Returns true if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method.
hasNextBigInteger()
Returns true if the next token in this scanner's input can be interpreted as a BigInteger in the default radix using the nextBigInteger() method.
hasNextBigInteger(int radix)
Returns true if the next token in this scanner's input can be interpreted as a BigInteger in the specified radix using the nextBigInteger() method.
hasNextBoolean()
This method checks if the Scanner object has boolean data type on its buffer.
hasNextByte()
This method returns true if the next byte on the scanner buffer can be translated to byte data type otherwise false.
hasNextByte(int radix)
Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified.
hasNextDouble()
Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method.
hasNextFloat()
Returns true if the next token in this scanner's input can be interpreted as a float value using the nextFloat() method.
hasNextInt()
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method.
hasNextInt(int radix)
This method returns boolean, true if the token can be interpreted as int data type with respect to the radix used by the scanner object otherwise false.
hasNextLine()
This method returns a boolean data type which corresponds to the existence of new line on the String tokens which the Scanner object holds.
hasNextLong()
Returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using the nextLong() method.
hasNextLong(int radix)
Returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using the nextLong() method.
hasNextShort()
Returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using the nextShort() method.
hasNextShort(int radix)
This method returns boolean, true if the token can be interpreted as short data type with respect to the radix used by the scanner object otherwise false.
ioException()
Returns the IOException last thrown by this Scanner's underlying Readable.
locale()
This method returns a Locale which the Scanner class is using.
match()
This method returns a MatchResult object which corresponds to the result of the last operation by the scanner object.
next(Pattern pattern)
Returns the next token if it matches the specified pattern.
radix()
Returns this scanner's default radix.
remove()
The remove operation is not supported by this implementation of Iterator.
reset()
Resets this scanner.
skip(Pattern pattern)
Skips input that matches the specified pattern, ignoring delimiters.
skip(String pattern)
Skips input that matches a pattern constructed from the specified string.
toString()
Returns the string representation of this Scanner.
useDelimiter(Pattern pattern)
Sets this scanner's delimiting pattern to the specified pattern.
useDelimiter(String pattern)
Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
useLocale(Locale locale)
Sets this scanner's locale to the specified locale.
useRadix(int radix)
Sets this scanner's default radix to the specified radix.

Scnner Class - I


The Scanner class is a class in java.util. Scanner class allows user to get input from keyboard.  Scanner class also having many other methods that helps to read a text files and also breaks the input into tokens using a delimiter, is whitespace considered as default delimiter.

Some methods of Scanner class for reading data.



String next() -               Read the input only till the space
String nextLine() -         Reads till the end of line ( till ‘\n’)
Int nextInt() -                Read a Integer data from System.in
byte nextByte() -          Read tokens in byte data type.
boolean nextBoolean() - Returns boolean data type
double nextDouble() -    Read next token of the input as a double.
float nextFloat() -          Read next token of the input as a Float.
long nextLong() -           Read next token of the input as a :ong.


Example:


import java.util.*;
import java.io.*;
    class Scanner_Read
        {
            public static void main(String args[])throws IOException
                {
                    Scanner Sc=new Scanner(System.in);
                    System.out.print("\n\tEnter a Word : ");
                    String s=Sc.next();
                    String s1=Sc.nextLine(); // Clearing Buffer
                    System.out.print("\n\tEnter a Sentence : ");
                    s1=Sc.nextLine();
                    System.out.print("\n\tEnter a Byte : ");
                    byte b=Sc.nextByte();
                    System.out.print("\n\tEnter an Integer Data : ");
                    int n=Sc.nextInt();
                    s1=Sc.nextLine(); // Clearing Buffer
                    System.out.print("\n\tEnter an Double Data : ");
                    double d=Sc.nextDouble();
                    System.out.print("\n\tEnter an Float Data : ");
                    float f=Sc.nextFloat();
                    System.out.print("\n\tEnter an Long Data : ");
                    long L=Sc.nextLong();
                    System.out.println("\n\tInput Data : ");
                    System.out.println("\tWord : "+s+" Sentence : "+s1+" Byte "+b);
                    System.out.println("\tInteger : "+n+" Double : "+d+" Long "+L+" Float :"+f);

                }
        }




Output:



          Enter a Word : Hello
          Enter a Sentence : Hello! Fine.
          Enter a Byte : 12
          Enter an Integer Data : 234
          Enter an Double Data : 34.56
          Enter an Float Data : 33.4
          Enter an Long Data : 343434

          Data :
          Word : Hello Sentence :  Byte 12
          Integer : 234 Double : 34.56 Long 343434 Float :33.4


Other Scanner Class Methods for reading data


nextBigDecimal() -                       Read the next token of the input as a BigDecimal.
nextBigInteger() -                         Read the next token of the input as a BigInteger.
nextBigInteger(int radix) -             Read the next token of the input as a BigInteger.
nextByte(int radix) -                     Read the next token of the input as a byte.
nextInt(int radix) -                        Read the next token of the input as an int.
nextLong() -                                 Read the next token of the input as a long.
nextLong(int radix) -                     Read the next token of the input as a long.
nextShort() -                                Read the next token of the input as a short.
nextShort(int radix) -                    Read the next token of the input as a short.







Thursday, April 3, 2014

StringTokenizer


StringTokenizer is class can be utilize to splitting the string into tokens. If no delimiter is mentioned then Whitespace will be taken as default delimiter but we can use multiple delimiter in StringTokenizer to split the tokens.

Methods

int countTokens() – Returns number of tokens in the String.
boolean hasMoreTokens() – Returns true if more tokens exists otherwise returns false.
String nextToken() - Returns the next token from the given the String.  
String nextToken(String delimiter) - returns the next token while switching to the new given delimiter.
boolean hasMoreElements() - Returns same as hasMoreTokens method.
Object nextElement()  - Returns same as nextToken but return value is an Object rather than String.

Example-1 : countTokens() / hasMoreTokens() / nextToken().


import java.util.*;

    public class StrTok_1
        {
            public static void main(String[] args)
                {
                    StringTokenizer st = new StringTokenizer("the brown dog jumped over the lazy fox");
                    System.out.println("\n\tTotal Numbers of tokens : " + st.countTokens());
                    System.out.println("\tTokens : " );
                    while (st.hasMoreTokens())
                        {
                            System.out.println("\t"+st.nextToken());   
                        }
     
                }
       }


Output



          Total Numbers of tokens : 8
          Tokens :
          the
          brown
          dog
          jumped
          over
          the
          lazy
          fox


Example-2 : hasMoreElements() / nextElement()

import java.util.*;

    public class StrTok_2
        {
            public static void main(String[] args)
                {
                    StringTokenizer st = new StringTokenizer("the brown dog jumped over the lazy fox");
                    System.out.println("\tTokens : " );
                    while (st.hasMoreElements())
                        {
                            System.out.println("\t"+st.nextElement());   
                        }
                  }
       }


Output



          Total Numbers of tokens : 8
          Tokens :
          the
          brown
          dog
          jumped
          over
          the
          lazy
          fox


Example_3 : nextToken(String Delimiter)
import java.util.*;

    public class StrTok_3
        {
            public static void main(String[] args)
                {
                    StringTokenizer st = new StringTokenizer("you,too,Brutus");
                    System.out.println("\tTokens (Delimited with , ) : " );
                    while (st.hasMoreTokens())
                        {
                            System.out.println("\t"+ st.nextToken(","));;   
                        }
                  }
       }


Output



          Tokens (Delimited with , ) :
          you
          too
          Brutus



Example_4 : Multiple Delimiter

import java.util.*;

    public class StrTok_4
        {
            public static void main(String[] args)
                {
                    StringTokenizer st = new StringTokenizer("Hi! I am fine. How are you?",".!?");
                    System.out.println("\n\tTotal Numbers of tokens : " + st.countTokens());
                    System.out.println("\tTokens (Delimiter . ! ? ): " );
                    while (st.hasMoreTokens())
                        {
                            System.out.println("\t"+st.nextToken().trim());   
                        }
                  }
       }



Output



          Total Numbers of tokens : 3
          Tokens (Delimiter . ! ? ):
          Hi
          I am fine
          How are you




String – III



 String.valueOf(String) - Returns a new Integer object initialized to the value of the specified

Example:

            String x="12";

            int y=Integer.valueOf(x);

String.toCharArray() -Converts this string to a new character array.

Example:

            String Str=”This is a test”;

            char ch[]=Str.toCharArray();

String copyValueOf(char[] dataItem, int offset, int count) : This function create a new string object from the contents stored in a character array.

            dataItem - is the given character array.

            offset - Starting position in the character  array. The position should be
            grater than 0 and less than the array length.

            count - Indicate the numbers of character to be picked from the character
            array.

Example:

            char[] chArr = new char[] { 'A', 'B', 'C', 'D','E','F' };
            String str = String.copyValueOf(chArr, 1, 3); //Returns "BCD"

boolean regionMatches(int, String,int,int) : Checks if specified region of a string matches with the another given region of the String argument and return Boolean.

Example:
      
            String str = "I live in India";
            String str1 = "I love India";

            boolean flag = str.regionMatches(10, str1, 7, 5); //Return true

toString() - Widely used when an object needed to represent as a string.'toString()' funcction returns the string representation of an object.

Example:

            Integer Num = 5;

            System.out.println(Num.toString()); 
                            
                                      or

             System.out.println(Integer.toString(375));