java.util

Class Scanner

Implemented Interfaces:
Iterator<E>

public final class Scanner
extends Object
implements Iterator<E>

A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

For example, this code allows a user to read a number from System.in:

     Scanner sc = new Scanner(System.in);
     int i = sc.nextInt();
 

As another example, this code allows long types to be assigned from entries in a file myNumbers:

      Scanner sc = new Scanner(new File("myNumbers"));
      while (sc.hasNextLong()) {
          long aLong = sc.nextLong();
      }

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

     String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
     System.out.println(s.nextInt());
     System.out.println(s.nextInt());
     System.out.println(s.next());
     System.out.println(s.next());
     s.close(); 

prints the following output:

     1
     2
     red
     blue 

The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:

     String input = "1 fish 2 fish red fish blue fish";
     Scanner s = new Scanner(input);
     s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
     MatchResult result = s.match();
     for (int i=1; i<=result.groupCount(); i++)
         System.out.println(result.group(i);
     s.close(); 

The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace.

A scanning operation may block waiting for input.

The next and hasNext methods and their primitive-type companion methods (such as nextInt and hasNextInt) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.

The findInLine, findWithinHorizon, and skip methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\\s" could return empty tokens since it only passes one space at a time.

A scanner can read text from any object which implements the Readable interface. If an invocation of the underlying readable's Readable.read(CharBuffer) method throws an IOException then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the ioException() method.

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

A Scanner is not safe for multithreaded use without external synchronization.

Unless otherwise mentioned, passing a null parameter into any method of a Scanner will cause a NullPointerException to be thrown.

A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the useRadix(int) method.

Localized numbers

An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the Locale.getDefault() method; it may be changed via the useLocale(Locale) method.

The localized formats are defined in terms of the following parameters, which for a particular locale are taken from that locale's DecimalFormat object, df, and its and DecimalFormatSymbols object, dfs.

LocalGroupSeparator  The character used to separate thousands groups, i.e., dfs.getGroupingSeparator()
LocalDecimalSeparator  The character used for the decimal point, i.e., dfs.getDecimalSeparator()
LocalPositivePrefix  The string that appears before a positive number (may be empty), i.e., df.getPositivePrefix()
LocalPositiveSuffix  The string that appears after a positive number (may be empty), i.e., df.getPositiveSuffix()
LocalNegativePrefix  The string that appears before a negative number (may be empty), i.e., df.getNegativePrefix()
LocalNegativeSuffix  The string that appears after a negative number (may be empty), i.e., df.getNegativeSuffix()
LocalNaN  The string that represents not-a-number for floating-point values, i.e., dfs.getInfinity()
LocalInfinity  The string that represents infinity for floating-point values, i.e., dfs.getInfinity()

Number syntax

The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10).

NonASCIIDigit  ::= A non-ASCII character c for which Character.isDigit(c) returns true
 
Non0Digit  ::= [1-Rmax] | NonASCIIDigit
 
Digit  ::= [0-Rmax] | NonASCIIDigit
 
GroupedNumeral  ::
= ( Non0Digit Digit? Digit?
LocalGroupSeparator Digit Digit Digit )+ )
  Numeral  ::= ( ( Digit+ ) | GroupedNumeral )  
Integer  ::= ( [-+]? ( Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix | LocalNegativePrefix Numeral LocalNegativeSuffix   DecimalNumeral  ::= Numeral | Numeral LocalDecimalSeparator Digit* | LocalDecimalSeparator Digit+   Exponent  ::= ( [eE] [+-]? Digit+ )   Decimal  ::= ( [-+]? DecimalNumeral Exponent? ) | LocalPositivePrefix DecimalNumeral LocalPositiveSuffix Exponent? | LocalNegativePrefix DecimalNumeral LocalNegativeSuffix Exponent?   HexFloat  ::= [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ ([pP][-+]?[0-9]+)?   NonNumber  ::= NaN | LocalNan | Infinity | LocalInfinity   SignedNonNumber  ::= ( [-+]? NonNumber ) | LocalPositivePrefix NonNumber LocalPositiveSuffix | LocalNegativePrefix NonNumber LocalNegativeSuffix   Float  ::= Decimal | HexFloat | SignedNonNumber

Whitespace is not significant in the above regular expressions.

Since:
1.5

Constructor Summary

Scanner(File source)
Constructs a new Scanner that produces values scanned from the specified file.
Scanner(File source, String charsetName)
Constructs a new Scanner that produces values scanned from the specified file.
Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream.
Scanner(InputStream source, String charsetName)
Constructs a new Scanner that produces values scanned from the specified input stream.
Scanner(Readable source)
Constructs a new Scanner that produces values scanned from the specified source.
Scanner(String source)
Constructs a new Scanner that produces values scanned from the specified string.
Scanner(ReadableByteChannel source)
Constructs a new Scanner that produces values scanned from the specified channel.
Scanner(ReadableByteChannel source, String charsetName)
Constructs a new Scanner that produces values scanned from the specified channel.

Method Summary

void
close()
Closes this scanner.
Pattern
delimiter()
Returns the Pattern this Scanner is currently using to match delimiters.
String
findInLine(String pattern)
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
String
findInLine(Pattern pattern)
Attempts to find the next occurrence of the specified pattern ignoring delimiters.
String
findWithinHorizon(String pattern, int horizon)
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
String
findWithinHorizon(Pattern pattern, int horizon)
Attempts to find the next occurrence of the specified pattern.
boolean
hasNext()
Returns true if this scanner has another token in its input.
boolean
hasNext(String pattern)
Returns true if the next token matches the pattern constructed from the specified string.
boolean
hasNext(Pattern pattern)
Returns true if the next complete token matches the specified pattern.
boolean
hasNextBigDecimal()
Returns true if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method.
boolean
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.
boolean
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.
boolean
hasNextBoolean()
Returns true if the next token in this scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false".
boolean
hasNextByte()
Returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using the nextByte method.
boolean
hasNextByte(int radix)
Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using the nextByte method.
boolean
hasNextDouble()
Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method.
boolean
hasNextFloat()
Returns true if the next token in this scanner's input can be interpreted as a float value using the nextFloat() method.
boolean
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.
boolean
hasNextInt(int radix)
Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt method.
boolean
hasNextLine()
Returns true if there is another line in the input of this scanner.
boolean
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.
boolean
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.
boolean
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.
boolean
hasNextShort(int radix)
Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using the nextShort method.
IOException
ioException()
Returns the IOException last thrown by this Scanner's underlying Readable.
Locale
locale()
Returns this scanner's locale.
MatchResult
match()
Returns the match result of the last scanning operation performed by this scanner.
String
next()
Finds and returns the next complete token from this scanner.
String
next(String pattern)
Returns the next token if it matches the pattern constructed from the specified string.
String
next(Pattern pattern)
Returns the next token if it matches the specified pattern.
BigDecimal
nextBigDecimal()
Scans the next token of the input as a BigDecimal.
BigInteger
nextBigInteger()
Scans the next token of the input as a BigInteger.
BigInteger
nextBigInteger(int radix)
Scans the next token of the input as a BigInteger.
boolean
nextBoolean()
Scans the next token of the input into a boolean value and returns that value.
byte
nextByte()
Scans the next token of the input as a byte.
byte
nextByte(int radix)
Scans the next token of the input as a byte.
double
nextDouble()
Scans the next token of the input as a double.
float
nextFloat()
Scans the next token of the input as a float.
int
nextInt()
Scans the next token of the input as an int.
int
nextInt(int radix)
Scans the next token of the input as an int.
String
nextLine()
Advances this scanner past the current line and returns the input that was skipped.
long
nextLong()
Scans the next token of the input as a long.
long
nextLong(int radix)
Scans the next token of the input as a long.
short
nextShort()
Scans the next token of the input as a short.
short
nextShort(int radix)
Scans the next token of the input as a short.
int
radix()
Returns this scanner's default radix.
void
remove()
The remove operation is not supported by this implementation of Iterator.
Scanner
skip(String pattern)
Skips input that matches a pattern constructed from the specified string.
Scanner
skip(Pattern pattern)
Skips input that matches the specified pattern, ignoring delimiters.
String
toString()
Returns the string representation of this Scanner.
Scanner
useDelimiter(String pattern)
Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
Scanner
useDelimiter(Pattern pattern)
Sets this scanner's delimiting pattern to the specified pattern.
Scanner
useLocale(Locale locale)
Sets this scanner's locale to the specified locale.
Scanner
useRadix(int radix)
Sets this scanner's default radix to the specified radix.

Methods inherited from class java.lang.Object

clone, equals, extends Object> getClass, finalize, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Details

Scanner

public Scanner(File source)
            throws FileNotFoundException
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
Parameters:
source - A file to be scanned
Throws:
FileNotFoundException - if source is not found
Usages and Demos :

View More Examples of Scanner(File source)
   1: 
   2:     Scanner s = new Scanner( p.getInputStream() ).useDelimiter( "\\Z" );
   3:     System.out.println( s.next() );
   4:   }
   5: }

View Full Code Here
   1:   {
   2:     MWST = new Scanner(LateConstant.class.getResourceAsStream("hubblekonstante.txt")).nextInt();
   3:   }
   4: 
   5:   LateConstant()

View Full Code Here
   1:     
   2:     Scanner s = new Scanner( proc.getInputStream() );
   3:     return s.findInLine( "\\p{XDigit}\\p{XDigit}(-\\p{XDigit}\\p{XDigit}){5}" );
   4:   }

View Full Code Here
   1:     FileReader fin = new FileReader("song.txt");
   2:     Scanner songIn = new Scanner(fin);
   3: 
   4:     name = songIn.nextLine();
   5:     duration = songIn.nextInt();

View Full Code Here
   1:       is = url.openStream();
   2:       System.out.println( new Scanner( is ).useDelimiter( "\\Z" ).next() );
   3:     }
   4:     catch ( Exception e )
   5:     {

View Full Code Here

Scanner

public Scanner(File source,
               String charsetName)
            throws FileNotFoundException
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset.
Parameters:
source - A file to be scanned
charsetName - The encoding type used to convert bytes from the file into characters to be scanned
Throws:
FileNotFoundException - if source is not found
IllegalArgumentException - if the specified encoding is not found

Scanner

public Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the underlying platform's default charset.
Parameters:
source - An input stream to be scanned
Usages and Demos :

View More Examples of Scanner(InputStream source)
   1: 
   2:     Scanner s = new Scanner( p.getInputStream() ).useDelimiter( "\\Z" );
   3:     System.out.println( s.next() );
   4:   }
   5: }

View Full Code Here
   1:   {
   2:     MWST = new Scanner(LateConstant.class.getResourceAsStream("hubblekonstante.txt")).nextInt();
   3:   }
   4: 
   5:   LateConstant()

View Full Code Here
   1:     
   2:     Scanner s = new Scanner( proc.getInputStream() );
   3:     return s.findInLine( "\\p{XDigit}\\p{XDigit}(-\\p{XDigit}\\p{XDigit}){5}" );
   4:   }

View Full Code Here
   1:     FileReader fin = new FileReader("song.txt");
   2:     Scanner songIn = new Scanner(fin);
   3: 
   4:     name = songIn.nextLine();
   5:     duration = songIn.nextInt();

View Full Code Here
   1:       is = url.openStream();
   2:       System.out.println( new Scanner( is ).useDelimiter( "\\Z" ).next() );
   3:     }
   4:     catch ( Exception e )
   5:     {

View Full Code Here

Scanner

public Scanner(InputStream source,
               String charsetName)
Constructs a new Scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the specified charset.
Parameters:
source - An input stream to be scanned
charsetName - The encoding type used to convert bytes from the stream into characters to be scanned
Throws:
IllegalArgumentException - if the specified character set does not exist

Scanner

public Scanner(Readable source)
Constructs a new Scanner that produces values scanned from the specified source.
Parameters:
source - A character source implementing the Readable interface
Usages and Demos :

View More Examples of Scanner(Readable source)
   1: 
   2:     Scanner s = new Scanner( p.getInputStream() ).useDelimiter( "\\Z" );
   3:     System.out.println( s.next() );
   4:   }
   5: }

View Full Code Here
   1:   {
   2:     MWST = new Scanner(LateConstant.class.getResourceAsStream("hubblekonstante.txt")).nextInt();
   3:   }
   4: 
   5:   LateConstant()

View Full Code Here
   1:     
   2:     Scanner s = new Scanner( proc.getInputStream() );
   3:     return s.findInLine( "\\p{XDigit}\\p{XDigit}(-\\p{XDigit}\\p{XDigit}){5}" );
   4:   }

View Full Code Here
   1:     FileReader fin = new FileReader("song.txt");
   2:     Scanner songIn = new Scanner(fin);
   3: 
   4:     name = songIn.nextLine();
   5:     duration = songIn.nextInt();

View Full Code Here
   1:       is = url.openStream();
   2:       System.out.println( new Scanner( is ).useDelimiter( "\\Z" ).next() );
   3:     }
   4:     catch ( Exception e )
   5:     {

View Full Code Here

Scanner

public Scanner(String source)
Constructs a new Scanner that produces values scanned from the specified string.
Parameters:
source - A string to scan
Usages and Demos :

View More Examples of Scanner(String source)
   1: 
   2:     Scanner s = new Scanner( p.getInputStream() ).useDelimiter( "\\Z" );
   3:     System.out.println( s.next() );
   4:   }
   5: }

View Full Code Here
   1:   {
   2:     MWST = new Scanner(LateConstant.class.getResourceAsStream("hubblekonstante.txt")).nextInt();
   3:   }
   4: 
   5:   LateConstant()

View Full Code Here
   1:     
   2:     Scanner s = new Scanner( proc.getInputStream() );
   3:     return s.findInLine( "\\p{XDigit}\\p{XDigit}(-\\p{XDigit}\\p{XDigit}){5}" );
   4:   }

View Full Code Here
   1:     FileReader fin = new FileReader("song.txt");
   2:     Scanner songIn = new Scanner(fin);
   3: 
   4:     name = songIn.nextLine();
   5:     duration = songIn.nextInt();

View Full Code Here
   1:       is = url.openStream();
   2:       System.out.println( new Scanner( is ).useDelimiter( "\\Z" ).next() );
   3:     }
   4:     catch ( Exception e )
   5:     {

View Full Code Here

Scanner

public Scanner(ReadableByteChannel source)
Constructs a new Scanner that produces values scanned from the specified channel. Bytes from the source are converted into characters using the underlying platform's default charset.
Parameters:
source - A channel to scan
Usages and Demos :

View More Examples of Scanner(ReadableByteChannel source)
   1: 
   2:     Scanner s = new Scanner( p.getInputStream() ).useDelimiter( "\\Z" );
   3:     System.out.println( s.next() );
   4:   }
   5: }

View Full Code Here
   1:   {
   2:     MWST = new Scanner(LateConstant.class.getResourceAsStream("hubblekonstante.txt")).nextInt();
   3:   }
   4: 
   5:   LateConstant()

View Full Code Here
   1:     
   2:     Scanner s = new Scanner( proc.getInputStream() );
   3:     return s.findInLine( "\\p{XDigit}\\p{XDigit}(-\\p{XDigit}\\p{XDigit}){5}" );
   4:   }

View Full Code Here
   1:     FileReader fin = new FileReader("song.txt");
   2:     Scanner songIn = new Scanner(fin);
   3: 
   4:     name = songIn.nextLine();
   5:     duration = songIn.nextInt();

View Full Code Here
   1:       is = url.openStream();
   2:       System.out.println( new Scanner( is ).useDelimiter( "\\Z" ).next() );
   3:     }
   4:     catch ( Exception e )
   5:     {

View Full Code Here

Scanner

public Scanner(ReadableByteChannel source,
               String charsetName)
Constructs a new Scanner that produces values scanned from the specified channel. Bytes from the source are converted into characters using the specified charset.
Parameters:
source - A channel to scan
charsetName - The encoding type used to convert bytes from the channel into characters to be scanned
Throws:
IllegalArgumentException - if the specified character set does not exist

Method Details

close

public void close()
Closes this scanner.

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.

Attempting to perform search operations after a scanner has been closed will result in an IllegalStateException.

Usages and Demos :

View More Examples of close()
   1: 
   2:     Scanner input = new Scanner(sourceFile);
   3:     StringBuilder sb = new StringBuilder();
   4:         ...
   5: 
   6:     input.close();
   7: 
   8:         ...
   9:     output.format("%s\r\n", sb.toString());
  10:     output.close();
  11:   }

View Full Code Here
   1:          fileText.setText("");
   2:          Scanner in = new Scanner(new FileReader(filename));
   3:          while (in.hasNextLine())
   4:         ...
   5:          fileText.append(in.nextLine() + "\n");
   6:          in.close();
   7:       }
   8:       catch (IOException e)
   9:       {  

View Full Code Here
   1:       if (!fileName.toLowerCase().endsWith(".txt")) return false;
   2:       Scanner in; 
   3:       try
   4:         ...
   5:       {
   6:          in = new Scanner(new FileReader(fileName));
   7:       }
   8:         ...
   9:          {
  10:             in.close();
  11:             System.out.println(fileName);

View Full Code Here
   1:          fileText.setText("");
   2:          Scanner in = new Scanner(new FileReader(filename));
   3:          while (in.hasNextLine()) fileText.append(in.nextLine() + "\n");
   4:         ...
   5:          in.close();
   6:       }
   7:       catch (IOException e)
   8:       {  

View Full Code Here
   1:    {
   2:       Scanner in = new Scanner(System.in);
   3:       System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");
   4:         ...
   5:       {
   6:          Scanner in = new Scanner(new FileInputStream(file));
   7:          boolean found = false;
   8:         ...
   9:          }
  10:          in.close();
  11:          return found;

View Full Code Here

delimiter

public Pattern delimiter()
Returns the Pattern this Scanner is currently using to match delimiters.
Returns:
this scanner's delimiting pattern.

findInLine

public String findInLine(String pattern)
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.

An invocation of this method of the form findInLine(pattern) behaves in exactly the same way as the invocation findInLine(Pattern.compile(pattern)).

Parameters:
pattern - a string specifying the pattern to search for
Returns:
the text that matched the specified pattern
Throws:
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of findInLine(String pattern)
   1: import java.io.IOException;
   2: import java.util.Scanner;
   3: 
   4:         ...
   5:     
   6:     Scanner s = new Scanner( proc.getInputStream() );
   7:         ...
   8:     return s.findInLine( "\\p{XDigit}\\p{XDigit}(-\\p{XDigit}\\p{XDigit}){5}" );
   9:   }

View Full Code Here

findInLine

public String findInLine(Pattern pattern)
Attempts to find the next occurrence of the specified pattern ignoring delimiters. If the pattern is found before the next line separator, the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected in the input up to the next line separator, then null is returned and the scanner's position is unchanged. This method may block waiting for input that matches the pattern.

Since this method continues to search through the input looking for the specified pattern, it may buffer all of the input searching for the desired token if no line separators are present.

Parameters:
pattern - the pattern to scan for
Returns:
the text that matched the specified pattern
Throws:
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of findInLine(Pattern pattern)
   1: import java.io.IOException;
   2: import java.util.Scanner;
   3: 
   4:         ...
   5:     
   6:     Scanner s = new Scanner( proc.getInputStream() );
   7:         ...
   8:     return s.findInLine( "\\p{XDigit}\\p{XDigit}(-\\p{XDigit}\\p{XDigit}){5}" );
   9:   }

View Full Code Here

findWithinHorizon

public String findWithinHorizon(String pattern,
                                int horizon)
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.

An invocation of this method of the form findWithinHorizon(pattern) behaves in exactly the same way as the invocation findWithinHorizon(Pattern.compile(pattern, horizon)).

Parameters:
pattern - a string specifying the pattern to search for
Returns:
the text that matched the specified pattern
Throws:
IllegalStateException - if this scanner is closed
IllegalArgumentException - if horizon is negative

findWithinHorizon

public String findWithinHorizon(Pattern pattern,
                                int horizon)
Attempts to find the next occurrence of the specified pattern.

This method searches through the input up to the specified search horizon, ignoring delimiters. If the pattern is found the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected then the null is returned and the scanner's position remains unchanged. This method may block waiting for input that matches the pattern.

A scanner will never search more than horizon code points beyond its current position. Note that a match may be clipped by the horizon; that is, an arbitrary match result may have been different if the horizon had been larger. The scanner treats the horizon as a transparent, non-anchoring bound (see Matcher.useTransparentBounds(boolean) and Matcher.useAnchoringBounds(boolean)).

If horizon is 0, then the horizon is ignored and this method continues to search through the input looking for the specified pattern without bound. In this case it may buffer all of the input searching for the pattern.

If horizon is negative, then an IllegalArgumentException is thrown.

Parameters:
pattern - the pattern to scan for
Returns:
the text that matched the specified pattern
Throws:
IllegalStateException - if this scanner is closed
IllegalArgumentException - if horizon is negative

hasNext

public boolean hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
Specified by:
hasNext in interface Iterator<E>
Returns:
true if and only if this scanner has another token
Throws:
IllegalStateException - if this scanner is closed
See Also:
Iterator
Usages and Demos :

View More Examples of hasNext()
   1:     System.out.println(Arrays.toString(input.split(" ")));
   2:     Scanner scanner = new Scanner(input);
   3:         ...
   4:     while(scanner.hasNext())
   5:       System.out.print(scanner.next() + " ");
   6:   }

View Full Code Here
   1: import java.util.Scanner;
   2: import java.util.regex.Pattern;
   3:         ...
   4:     Pattern had = Pattern.compile(regex);
   5:     Scanner strScan = new Scanner(str);
   6:     int hadCount = 0;
   7:         ...
   8:     while(strScan.hasNext()) {
   9:       if(strScan.hasNext(had)) {

View Full Code Here
   1: 
   2:     Scanner input = new Scanner(sourceFile);
   3:     StringBuilder sb = new StringBuilder();
   4:         ...
   5: 
   6:     while (input.hasNext()) {
   7:       String s1 = input.nextLine();
   8:       String s2 = s1.replaceAll(args[1], "");
   9:       sb.append("\r\n" + s2);

View Full Code Here
   1:   public static void main(String[] args) {
   2:     Scanner s = new Scanner(new RandomWords(10));
   3:         ...
   4:     while(s.hasNext())
   5:       System.out.println(s.next());
   6:   }

View Full Code Here
   1: import java.io.FileNotFoundException;
   2: import java.util.Scanner;
   3: 
   4:         ...
   5:             new TreeMap<String, TreeSet<String>>();
   6:         Scanner fin = null;
   7:         TreeSet<String> prodSet;
   8:         ...
   9:         {
  10:             fin = new Scanner(new FileReader("product.dat"));
  11:             fin.useDelimiter("[\t\n\r]+");
  12:         ...
  13: 
  14:         while(fin.hasNext())

View Full Code Here

hasNext

public boolean hasNext(String pattern)
Returns true if the next token matches the pattern constructed from the specified string. The scanner does not advance past any input.

An invocation of this method of the form hasNext(pattern) behaves in exactly the same way as the invocation hasNext(Pattern.compile(pattern)).

Parameters:
pattern - a string specifying the pattern to scan
Returns:
true if and only if this scanner has another token matching the specified pattern
Throws:
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of hasNext(String pattern)
   1:   public static void main(String[] args) {
   2:     Scanner scanner = new Scanner(threatData);
   3:     String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@" +
   4:         ...
   5:       "(\\d{2}/\\d{2}/\\d{4})";
   6:     while(scanner.hasNext(pattern)) {
   7:       scanner.next(pattern);
   8:       MatchResult match = scanner.match();
   9:       String ip = match.group(1);

View Full Code Here

hasNext

public boolean hasNext(Pattern pattern)
Returns true if the next complete token matches the specified pattern. A complete token is prefixed and postfixed by input that matches the delimiter pattern. This method may block while waiting for input. The scanner does not advance past any input.
Parameters:
pattern - the pattern to scan for
Returns:
true if and only if this scanner has another token matching the specified pattern
Throws:
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of hasNext(Pattern pattern)
   1:   public static void main(String[] args) {
   2:     Scanner scanner = new Scanner(threatData);
   3:     String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@" +
   4:         ...
   5:       "(\\d{2}/\\d{2}/\\d{4})";
   6:     while(scanner.hasNext(pattern)) {
   7:       scanner.next(pattern);
   8:       MatchResult match = scanner.match();
   9:       String ip = match.group(1);

View Full Code Here

hasNextBigDecimal

public boolean hasNextBigDecimal()
Returns true if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid BigDecimal
Throws:
IllegalStateException - if this scanner is closed

hasNextBigInteger

public boolean 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. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid BigInteger
Throws:
IllegalStateException - if this scanner is closed

hasNextBigInteger

public boolean 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. The scanner does not advance past any input.
Parameters:
radix - the radix used to interpret the token as an integer
Returns:
true if and only if this scanner's next token is a valid BigInteger
Throws:
IllegalStateException - if this scanner is closed

hasNextBoolean

public boolean hasNextBoolean()
Returns true if the next token in this scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false". The scanner does not advance past the input that matched.
Returns:
true if and only if this scanner's next token is a valid boolean value
Throws:
IllegalStateException - if this scanner is closed

hasNextByte

public boolean hasNextByte()
Returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using the nextByte method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid byte value
Throws:
IllegalStateException - if this scanner is closed

hasNextByte

public boolean hasNextByte(int radix)
Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using the nextByte method. The scanner does not advance past any input.
Parameters:
radix - the radix used to interpret the token as a byte value
Returns:
true if and only if this scanner's next token is a valid byte value
Throws:
IllegalStateException - if this scanner is closed

hasNextDouble

public boolean hasNextDouble()
Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid double value
Throws:
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of hasNextDouble()
   1:   public static void main(String[] args) {
   2:     Scanner s = new Scanner(new AdaptedRandomDoubles(7));
   3:         ...
   4:     while(s.hasNextDouble())
   5:       System.out.print(s.nextDouble() + " ");
   6:   }

View Full Code Here

hasNextFloat

public boolean hasNextFloat()
Returns true if the next token in this scanner's input can be interpreted as a float value using the nextFloat() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid float value
Throws:
IllegalStateException - if this scanner is closed

hasNextInt

public boolean 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. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid int value
Throws:
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of hasNextInt()
   1:   public static void main(String[] args) {
   2:     Scanner scanner = new Scanner("12, 42, 78, 99, 42");
   3:     scanner.useDelimiter("\\s*,\\s*");
   4:         ...
   5:     while(scanner.hasNextInt())
   6:       System.out.println(scanner.nextInt());
   7:   }

View Full Code Here
   1: {
   2:     static Scanner sc = new Scanner(System.in);
   3: 
   4:         ...
   5:     {
   6:         while (!sc.hasNextInt())
   7:         {
   8:             sc.nextLine();
   9:             System.out.print("That's not an integer. "

View Full Code Here

hasNextInt

public boolean hasNextInt(int radix)
Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt method. The scanner does not advance past any input.
Parameters:
radix - the radix used to interpret the token as an int value
Returns:
true if and only if this scanner's next token is a valid int value
Throws:
IllegalStateException - if this scanner is closed

hasNextLine

public boolean hasNextLine()
Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.
Returns:
true if and only if this scanner has another line of input
Throws:
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of hasNextLine()
   1:             InputStream inStream = s.getInputStream();
   2:             Scanner in = new Scanner(inStream);
   3:             
   4:         ...
   5:             while (in.hasNextLine())
   6:             {  
   7:                String line = in.nextLine();
   8:                System.out.println(line);

View Full Code Here
   1:          fileText.setText("");
   2:          Scanner in = new Scanner(new FileReader(filename));
   3:         ...
   4:          while (in.hasNextLine())
   5:          fileText.append(in.nextLine() + "\n");
   6:          in.close();
   7:       }

View Full Code Here
   1:          fileText.setText("");
   2:          Scanner in = new Scanner(new FileReader(filename));
   3:         ...
   4:          while (in.hasNextLine()) fileText.append(in.nextLine() + "\n");
   5:          in.close();
   6:       }
   7:       catch (IOException e)

View Full Code Here
   1:             FileWriter temp = new FileWriter(tempFile);
   2:             Scanner scanner = new Scanner(new File(checkerDir + "/" + javaFile));
   3:         ...
   4:             while (scanner.hasNextLine()) {
   5:                 String s = scanner.nextLine();
   6:                 s = s.replaceAll("public\\s+class", "class");
   7:                 s = s.replaceAll("(?<!new )@Mutable", "");

View Full Code Here
   1:    {
   2:       Scanner in = new Scanner(System.in);
   3:       System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");
   4:         ...
   5:       {
   6:          Scanner in = new Scanner(new FileInputStream(file));
   7:          boolean found = false;
   8:         ...
   9:          while (!found && in.hasNextLine())
  10:          {

View Full Code Here

hasNextLong

public boolean 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. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid long value
Throws:
IllegalStateException - if this scanner is closed

hasNextLong

public boolean 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. The scanner does not advance past any input.
Parameters:
radix - the radix used to interpret the token as a long value
Returns:
true if and only if this scanner's next token is a valid long value
Throws:
IllegalStateException - if this scanner is closed

hasNextShort

public boolean 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. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid short value in the default radix
Throws:
IllegalStateException - if this scanner is closed

hasNextShort

public boolean hasNextShort(int radix)
Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using the nextShort method. The scanner does not advance past any input.
Parameters:
radix - the radix used to interpret the token as a short value
Returns:
true if and only if this scanner's next token is a valid short value in the specified radix
Throws:
IllegalStateException - if this scanner is closed

ioException

public IOException ioException()
Returns the IOException last thrown by this Scanner's underlying Readable. This method returns null if no such exception exists.
Returns:
the last exception thrown by this scanner's readable

locale

public Locale locale()
Returns this scanner's locale.

A scanner's locale affects many elements of its default primitive matching regular expressions; see localized numbers above.

Returns:
this scanner's locale

match

public MatchResult match()
Returns the match result of the last scanning operation performed by this scanner. This method throws IllegalStateException if no match has been performed, or if the last match was not successful.

The various nextmethods of Scanner make a match result available if they complete without throwing an exception. For instance, after an invocation of the nextInt method that returned an int, this method returns a MatchResult for the search of the Integer regular expression defined above. Similarly the findInLine, findWithinHorizon, and skip methods will make a match available if they succeed.

Returns:
a match result for the last match operation
Throws:
IllegalStateException - If no match result is available
Usages and Demos :

View More Examples of match()
   1:   public static void main(String[] args) {
   2:     Scanner scanner = new Scanner(threatData);
   3:     String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@" +
   4:         ...
   5:       scanner.next(pattern);
   6:       MatchResult match = scanner.match();
   7:       String ip = match.group(1);
   8:       String date = match.group(2);
   9:       System.out.format("Threat on %s from %s\n", date,ip);

View Full Code Here

next

public String next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext returned true.
Specified by:
next in interface Iterator<E>
Returns:
the next token
Throws:
NoSuchElementException - if no more tokens are available
IllegalStateException - if this scanner is closed
See Also:
Iterator
Usages and Demos :

View More Examples of next()
   1: {
   2:     static Scanner sc = new Scanner(System.in);
   3: 
   4:         ...
   5:             {
   6:                 sc.next();
   7:                 System.out.print("That's not an integer. "
   8:                     + "Try again: ");
   9:             }

View Full Code Here
   1: import java.io.FileNotFoundException;
   2: import java.util.Scanner;
   3: 
   4:         ...
   5:             new TreeMap<String, TreeSet<String>>();
   6:         Scanner fin = null;
   7:         TreeSet<String> prodSet;
   8:         ...
   9:         {
  10:             fin = new Scanner(new FileReader("product.dat"));
  11:             fin.useDelimiter("[\t\n\r]+");
  12:         ...
  13:         {
  14:             company = fin.next();

View Full Code Here
   1: import ch03.stacks.*;
   2: import java.util.Scanner;
   3: 
   4:         ...
   5: 
   6:     Scanner tokenizer = new Scanner(expression);
   7: 
   8:         ...
   9:       {
  10:         operator = tokenizer.next();
  11:         

View Full Code Here
   1: import ds.util.LinkedList;
   2: import java.util.Scanner;
   3: 
   4:         ...
   5:         String[] playerArr ={"Jones", "Hardy", "Donovan", "Bundy"};
   6:         Scanner keyIn = new Scanner(System.in);
   7:         String inputStr;
   8:         ...
   9:             System.out.print("   Update: ");
  10:             updateAction = keyIn.next().charAt(0);
  11: 
  12:         ...
  13:                 case 'a':     
  14:                     playerName = keyIn.next();

View Full Code Here
   1: import java.io.FileNotFoundException;
   2: import java.util.Scanner;
   3: 
   4:         ...
   5: {
   6:     static Scanner keyIn = new Scanner(System.in);
   7: 
   8:         ...
   9:         System.out.print("Enter the document to spell check: ");
  10:         fileName = keyIn.next();
  11: 
  12:         ...
  13:         {
  14:             word = dictFile.next();

View Full Code Here

next

public String next(String pattern)
Returns the next token if it matches the pattern constructed from the specified string. If the match is successful, the scanner advances past the input that matched the pattern.

An invocation of this method of the form next(pattern) behaves in exactly the same way as the invocation next(Pattern.compile(pattern)).

Parameters:
pattern - a string specifying the pattern to scan
Returns:
the next token
Throws:
NoSuchElementException - if no such tokens are available
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of next(String pattern)
   1:   public static void main(String[] args) {
   2:     Scanner scanner = new Scanner(threatData);
   3:     String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@" +
   4:         ...
   5:     while(scanner.hasNext(pattern)) {
   6:       scanner.next(pattern);
   7:       MatchResult match = scanner.match();
   8:       String ip = match.group(1);
   9:       String date = match.group(2);

View Full Code Here

next

public String next(Pattern pattern)
Returns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext(Pattern) returned true. If the match is successful, the scanner advances past the input that matched the pattern.
Parameters:
pattern - the pattern to scan for
Returns:
the next token
Throws:
NoSuchElementException - if no more tokens are available
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of next(Pattern pattern)
   1:   public static void main(String[] args) {
   2:     Scanner scanner = new Scanner(threatData);
   3:     String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@" +
   4:         ...
   5:     while(scanner.hasNext(pattern)) {
   6:       scanner.next(pattern);
   7:       MatchResult match = scanner.match();
   8:       String ip = match.group(1);
   9:       String date = match.group(2);

View Full Code Here

nextBigDecimal

public BigDecimal nextBigDecimal()
Scans the next token of the input as a BigDecimal.

If the next token matches the Decimal regular expression defined above then the token is converted into a BigDecimal value as if by removing all group separators, mapping non-ASCII digits into ASCII digits via the Character.digit, and passing the resulting string to the BigDecimal(String) constructor.

Returns:
the BigDecimal scanned from the input
Throws:
InputMismatchException - if the next token does not match the Decimal regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed

nextBigInteger

public BigInteger nextBigInteger()
Scans the next token of the input as a BigInteger.

An invocation of this method of the form nextBigInteger() behaves in exactly the same way as the invocation nextBigInteger(radix), where radix is the default radix of this scanner.

Returns:
the BigInteger scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed

nextBigInteger

public BigInteger nextBigInteger(int radix)
Scans the next token of the input as a BigInteger.

If the next token matches the Integer regular expression defined above then the token is converted into a BigInteger value as if by removing all group separators, mapping non-ASCII digits into ASCII digits via the Character.digit, and passing the resulting string to the BigInteger(String, int) constructor with the specified radix.

Parameters:
radix - the radix used to interpret the token
Returns:
the BigInteger scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed

nextBoolean

public boolean nextBoolean()
Scans the next token of the input into a boolean value and returns that value. This method will throw InputMismatchException if the next token cannot be translated into a valid boolean value. If the match is successful, the scanner advances past the input that matched.
Returns:
the boolean scanned from the input
Throws:
InputMismatchException - if the next token is not a valid boolean
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

nextByte

public byte nextByte()
Scans the next token of the input as a byte.

An invocation of this method of the form nextByte() behaves in exactly the same way as the invocation nextByte(radix), where radix is the default radix of this scanner.

Returns:
the byte scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

nextByte

public byte nextByte(int radix)
Scans the next token of the input as a byte. This method will throw InputMismatchException if the next token cannot be translated into a valid byte value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Integer regular expression defined above then the token is converted into a byte value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Byte.parseByte with the specified radix.

Parameters:
radix - the radix used to interpret the token as a byte value
Returns:
the byte scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

nextDouble

public double nextDouble()
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Float regular expression defined above then the token is converted into a double value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Double.parseDouble. If the token matches the localized NaN or infinity strings, then either "Nan" or "Infinity" is passed to Double.parseDouble as appropriate.

Returns:
the double scanned from the input
Throws:
InputMismatchException - if the next token does not match the Float regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of nextDouble()
   1: 
   2: import java.util.Scanner;
   3: 
   4:         ...
   5: 
   6:     static Scanner sc = new Scanner(System.in);
   7: 
   8:         ...
   9:         System.out.print("Enter the radius of your circle: ");
  10:         double r = sc.nextDouble();
  11:         double area = Math.PI * (r * r);

View Full Code Here
   1:    {
   2:       Scanner in = new Scanner(System.in);
   3: 
   4:         ...
   5:       System.out.print("How much money do you need to retire? ");
   6:       double goal = in.nextDouble();
   7: 
   8:         ...
   9:       System.out.print("How much money will you contribute every year? ");
  10:       double payment = in.nextDouble();
  11: 
  12:         ...
  13:       System.out.print("Interest rate in %: ");
  14:       double interestRate = in.nextDouble();

View Full Code Here
   1: {
   2:     static Scanner sc = new Scanner(System.in);
   3:     static NumberFormat cf = NumberFormat.getCurrencyInstance();
   4:         ...
   5:             System.out.print("\nEnter subtotal: ");
   6:             subTotal = sc.nextDouble();
   7:             sc.nextLine();
   8: 
   9:             salesTax = subTotal * taxRate;

View Full Code Here
   1:    {
   2:       Scanner in = new Scanner(System.in);
   3: 
   4:         ...
   5:       System.out.print("How much money will you contribute every year? ");
   6:       double payment = in.nextDouble();
   7: 
   8:         ...
   9:       System.out.print("Interest rate in %: ");
  10:       double interestRate = in.nextDouble();

View Full Code Here
   1: import java.util.Scanner;
   2: 
   3:         ...
   4:   public static void main(String args[]) {
   5:     Scanner scanner = new Scanner(System.in);
   6: 
   7:         ...
   8:     System.out.print("Enter number of hours worked in a week: ");
   9:     double hours = scanner.nextDouble();
  10: 
  11:         ...
  12:     System.out.print("Enter hourly pay rate: ");
  13:     double payRate = scanner.nextDouble();

View Full Code Here

nextFloat

public float nextFloat()
Scans the next token of the input as a float. This method will throw InputMismatchException if the next token cannot be translated into a valid float value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Float regular expression defined above then the token is converted into a float value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Float.parseFloat. If the token matches the localized NaN or infinity strings, then either "Nan" or "Infinity" is passed to Float.parseFloat as appropriate.

Returns:
the float scanned from the input
Throws:
InputMismatchException - if the next token does not match the Float regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

nextInt

public int nextInt()
Scans the next token of the input as an int.

An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.

Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of nextInt()
   1: {
   2:     static Scanner sc = new Scanner(System.in);
   3: 
   4:         ...
   5:         }
   6:         return sc.nextInt();
   7:     }
   8: 
   9: }

View Full Code Here
   1: {
   2:     static Scanner sc = new Scanner(System.in);
   3: 
   4:         ...
   5:             {
   6:                 return sc.nextInt();
   7:             }
   8:             catch (InputMismatchException e)
   9:             {

View Full Code Here
   1:    {  
   2:       Scanner in = new Scanner(System.in);
   3: 
   4:         ...
   5:       System.out.print("How many numbers do you need to draw? ");
   6:       int k = in.nextInt();
   7:       
   8:         ...
   9:       System.out.print("What is the highest number you can draw? ");
  10:       int n = in.nextInt();

View Full Code Here
   1:    {  
   2:       Scanner in = new Scanner(System.in);
   3: 
   4:         ...
   5:       System.out.print("How many numbers do you need to draw? ");
   6:       int k = in.nextInt();
   7:       
   8:         ...
   9:       System.out.print("What is the highest number you can draw? ");
  10:       int n = in.nextInt();

View Full Code Here
   1:    {  
   2:       Scanner in = new Scanner(System.in);
   3: 
   4:         ...
   5:       System.out.print("How many numbers do you need to draw? ");
   6:       int k = in.nextInt();
   7:       
   8:         ...
   9:       System.out.print("What is the highest number you can draw? ");
  10:       int n = in.nextInt();

View Full Code Here

nextInt

public int nextInt(int radix)
Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Integer regular expression defined above then the token is converted into an int value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Integer.parseInt with the specified radix.

Parameters:
radix - the radix used to interpret the token as an int value
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

nextLine

public String nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

Returns:
the line that was skipped
Throws:
NoSuchElementException - if no line was found
IllegalStateException - if this scanner is closed
Usages and Demos :

View More Examples of nextLine()
   1: {
   2:     static Scanner sc = new Scanner(System.in);
   3: 
   4:         ...
   5:         {
   6:             sc.nextLine();
   7:             System.out.print("That's not an integer. "
   8:                 + "Try again: ");
   9:         }

View Full Code Here
   1: {
   2:     static Scanner sc = new Scanner(System.in);
   3:     static NumberFormat cf = NumberFormat.getCurrencyInstance();
   4:         ...
   5:             subTotal = sc.nextDouble();
   6:             sc.nextLine();
   7: 
   8:         ...
   9:         System.out.print("\nAgain? (Y or N) ");
  10:         if (sc.nextLine().equalsIgnoreCase("Y"))
  11:             return true;

View Full Code Here
   1: 
   2: import java.util.Scanner;
   3: 
   4:         ...
   5:   {
   6:     Scanner conIn = new Scanner(System.in);
   7: 
   8:         ...
   9:       System.out.println("Enter a string to be evaluated: ");
  10:       candidate = conIn.nextLine();
  11:       
  12:         ...
  13:       System.out.print("Evaluate another string? (Y=Yes): ");
  14:       more = conIn.nextLine();

View Full Code Here
   1: 
   2:             Scanner in =
   3:         ...
   4:                 new Scanner(s.getInputStream());
   5:             PrintWriter out;
   6:         ...
   7: 
   8:             in.nextLine();
   9: 
  10:         ...
  11:             in.nextLine();

View Full Code Here
   1: 
   2: import java.util.Scanner;
   3: import ch03.postfix.*;
   4:         ...
   5:   {
   6:     Scanner conIn = new Scanner(System.in);
   7: 
   8:         ...
   9:       System.out.println("Enter a postfix expression to be evaluated: ");
  10:       line = conIn.nextLine();
  11:       
  12:         ...
  13:       System.out.print("Evaluate another expression? (Y=Yes): ");
  14:       more = conIn.nextLine();

View Full Code Here

nextLong

public long nextLong()
Scans the next token of the input as a long.

An invocation of this method of the form nextLong() behaves in exactly the same way as the invocation nextLong(radix), where radix is the default radix of this scanner.

Returns:
the long scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

nextLong

public long nextLong(int radix)
Scans the next token of the input as a long. This method will throw InputMismatchException if the next token cannot be translated into a valid long value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Integer regular expression defined above then the token is converted into an long value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Long.parseLong with the specified radix.

Parameters:
radix - the radix used to interpret the token as an int value
Returns:
the long scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

nextShort

public short nextShort()
Scans the next token of the input as a short.

An invocation of this method of the form nextShort() behaves in exactly the same way as the invocation nextShort(radix), where radix is the default radix of this scanner.

Returns:
the short scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

nextShort

public short nextShort(int radix)
Scans the next token of the input as a short. This method will throw InputMismatchException if the next token cannot be translated into a valid short value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Integer regular expression defined above then the token is converted into a short value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Short.parseShort with the specified radix.

Parameters:
radix - the radix used to interpret the token as a short value
Returns:
the short scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

radix

public int radix()
Returns this scanner's default radix.

A scanner's radix affects elements of its default number matching regular expressions; see localized numbers above.

Returns:
the default radix of this scanner

remove

public void remove()
The remove operation is not supported by this implementation of Iterator.
Specified by:
remove in interface Iterator<E>
Throws:
UnsupportedOperationException - if this method is invoked.
See Also:
Iterator

skip

public Scanner skip(String pattern)
Skips input that matches a pattern constructed from the specified string.

An invocation of this method of the form skip(pattern) behaves in exactly the same way as the invocation skip(Pattern.compile(pattern)).

Parameters:
pattern - a string specifying the pattern to skip over
Returns:
this scanner
Throws:
IllegalStateException - if this scanner is closed

skip

public Scanner skip(Pattern pattern)
Skips input that matches the specified pattern, ignoring delimiters. This method will skip input if an anchored match of the specified pattern succeeds.

If a match to the specified pattern is not found at the current position, then no input is skipped and a NoSuchElementException is thrown.

Since this method seeks to match the specified pattern starting at the scanner's current position, patterns that can match a lot of input (".*", for example) may cause the scanner to buffer a large amount of input.

Note that it is possible to skip something without risking a NoSuchElementException by using a pattern that can match nothing, e.g., sc.skip("[ \t]*").

Parameters:
pattern - a string specifying the pattern to skip over
Returns:
this scanner
Throws:
NoSuchElementException - if the specified pattern is not found
IllegalStateException - if this scanner is closed

toString

public String toString()
Returns the string representation of this Scanner. The string representation of a Scanner contains information that may be useful for debugging. The exact format is unspecified.
Overrides:
toString in interface Object
Returns:
The string representation of this scanner

useDelimiter

public Scanner useDelimiter(String pattern)
Sets this scanner's delimiting pattern to a pattern constructed from the specified String.

An invocation of this method of the form useDelimiter(pattern) behaves in exactly the same way as the invocation hasDelimiter(Pattern.compile(pattern)).

Parameters:
pattern - A string specifying a delimiting pattern
Returns:
this scanner
Usages and Demos :

View More Examples of useDelimiter(String pattern)
   1: import java.io.FileNotFoundException;
   2: import java.util.Scanner;
   3: 
   4:         ...
   5:             new TreeMap<String, TreeSet<String>>();
   6:         Scanner fin = null;
   7:         TreeSet<String> prodSet;
   8:         ...
   9:         {
  10:             fin = new Scanner(new FileReader("product.dat"));
  11:         ...
  12:             fin.useDelimiter("[\t\n\r]+");

View Full Code Here
   1:     FileReader fin = new FileReader("words.dat");
   2:     Scanner wordsIn = new Scanner(fin);
   3: 
   4:         ...
   5:     Scanner conIn = new Scanner(System.in);
   6: 
   7:     System.out.print("Minimum word size: ");
   8:     minSize = conIn.nextInt();

View Full Code Here
   1: import java.util.List;
   2: import java.util.Scanner;
   3: import java.util.Set;
   4:         ...
   5:                 }
   6:                 Scanner scanner = new Scanner(is);
   7:         ...
   8:                 scanner.useDelimiter("\n");
   9:                 while (scanner.hasNext()) {

View Full Code Here
   1: 
   2: import java.util.Scanner;
   3: import java.util.regex.Pattern;
   4:         ...
   5:                         else{
   6:                             Scanner scan = new Scanner(value);
   7:         ...
   8:                             scan.useDelimiter(Pattern.compile("\\s|<|>")); 
   9:                             

View Full Code Here
   1: import java.util.List;
   2: import java.util.Scanner;
   3: import javax.xml.bind.JAXBContext;
   4:         ...
   5:             Link link = new Link();
   6:             Scanner scanner = new Scanner(reader);
   7:         ...
   8:             scanner.useDelimiter("\\<");
   9:             String token;

View Full Code Here

useDelimiter

public Scanner useDelimiter(Pattern pattern)
Sets this scanner's delimiting pattern to the specified pattern.
Parameters:
pattern - A delimiting pattern
Returns:
this scanner
Usages and Demos :

View More Examples of useDelimiter(Pattern pattern)
   1: import java.io.FileNotFoundException;
   2: import java.util.Scanner;
   3: 
   4:         ...
   5:             new TreeMap<String, TreeSet<String>>();
   6:         Scanner fin = null;
   7:         TreeSet<String> prodSet;
   8:         ...
   9:         {
  10:             fin = new Scanner(new FileReader("product.dat"));
  11:         ...
  12:             fin.useDelimiter("[\t\n\r]+");

View Full Code Here
   1:     FileReader fin = new FileReader("words.dat");
   2:     Scanner wordsIn = new Scanner(fin);
   3: 
   4:         ...
   5:     Scanner conIn = new Scanner(System.in);
   6: 
   7:     System.out.print("Minimum word size: ");
   8:     minSize = conIn.nextInt();

View Full Code Here
   1: import java.util.List;
   2: import java.util.Scanner;
   3: import java.util.Set;
   4:         ...
   5:                 }
   6:                 Scanner scanner = new Scanner(is);
   7:         ...
   8:                 scanner.useDelimiter("\n");
   9:                 while (scanner.hasNext()) {

View Full Code Here
   1: 
   2: import java.util.Scanner;
   3: import java.util.regex.Pattern;
   4:         ...
   5:                         else{
   6:                             Scanner scan = new Scanner(value);
   7:         ...
   8:                             scan.useDelimiter(Pattern.compile("\\s|<|>")); 
   9:                             

View Full Code Here
   1: import java.util.List;
   2: import java.util.Scanner;
   3: import javax.xml.bind.JAXBContext;
   4:         ...
   5:             Link link = new Link();
   6:             Scanner scanner = new Scanner(reader);
   7:         ...
   8:             scanner.useDelimiter("\\<");
   9:             String token;

View Full Code Here

useLocale

public Scanner useLocale(Locale locale)
Sets this scanner's locale to the specified locale.

A scanner's locale affects many elements of its default primitive matching regular expressions; see localized numbers above.

Parameters:
locale - A string specifying the locale to use
Returns:
this scanner

useRadix

public Scanner useRadix(int radix)
Sets this scanner's default radix to the specified radix.

A scanner's radix affects elements of its default number matching regular expressions; see localized numbers above.

If the radix is less than Character.MIN_RADIX or greater than Character.MAX_RADIX, then an IllegalArgumentException is thrown.

Parameters:
radix - The radix to use when scanning numbers
Returns:
this scanner
Throws:
IllegalArgumentException - if radix is out of range