Source of TestScannerWithString.java


  1: //TestScannerWithString.java
  2: 
  3: import java.util.Scanner;
  4: 
  5: public class TestScannerWithString
  6: {
  7:     public static void main(String args[])
  8:     {
  9:         //Initializing a Scanner with a String
 10:         String s = "The quick brown fox jumped over the lazy dogs.";
 11:         Scanner stringStream = new Scanner(s);
 12:         while (stringStream.hasNext())
 13:         {
 14:             System.out.println(stringStream.next());
 15:         }
 16: 
 17:         //Initializing a Scanner with a String containing integers
 18:         String stringOfInts = "1 2 3 4 5";
 19:         Scanner intReader = new Scanner(stringOfInts);
 20:         int sum = 0;
 21:         while (intReader.hasNext())
 22:         {
 23:             sum += Integer.parseInt(intReader.next());
 24:         }
 25:         System.out.println(sum);
 26: 
 27:         //Using a differenct delimiter
 28:         String anotherStringOfInts = "1!2!3!4!6";
 29:         Scanner anotherIntReader = new Scanner(anotherStringOfInts);
 30:         anotherIntReader.useDelimiter("!");
 31:         sum = 0;
 32:         while (anotherIntReader.hasNext())
 33:         {
 34:             sum += Integer.parseInt(anotherIntReader.next());
 35:         }
 36:         System.out.println(sum);
 37:     }
 38: }
 39: