Java Scaner class details _ Power node Java College collation

  • 2020-07-21 07:36:56
  • OfStack

Java.util.Scanner is a new feature of Java5.0. Its main function is to simplify text scanning. The most useful aspect of this class is the ability to get console input. The rest of the functionality is trivial, although the Java API documentation lists a number of API methods, none of which are very impressive.

1. Scan the console input

This example is often used, but without Scanner, you know how hard it is to write.

When you create an Scanner via new Scanner(System.in), the console waits for input until you hit enter, passing it to Scanner as a scan object. To get the input, you simply call the nextLine() method of Scanner.


/** 
*  Scan console input  
* 
*/ 
public class TestScanner { 
    public static void main(String[] args) { 
        Scanner s = new Scanner(System.in); 
        System.out.println(" Please enter the string: "); 
        while (true) { 
            String line = s.nextLine(); 
            if (line.equals("exit")) break; 
            System.out.println(">>>" + line); 
        } 
    } 
}

Please enter the string:

234
> > > 234
wer
> > > wer
bye
> > > bye
exit

Process finished with exit code 0

2. If Scanner is easy to use, it's better that Scanner's constructor supports multiple ways to build Scanner objects.

You can build Scanner objects directly from strings (Readable), input streams, files, and so on. With Scanner, you can scan the entire text segment by segment (according to the regular separator) and do whatever you want with the scanned results.

Scanner USES a space as a delimiter to separate text by default, but allows you to specify new delimiters

Use the default space separator:


    public static void main(String[] args) throws FileNotFoundException { 
        Scanner s = new Scanner("123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf  ......asdfkl  las"); 
//        s.useDelimiter(" |,|\\."); 
        while (s.hasNext()) { 
            System.out.println(s.next()); 
        } 
    }

123
asdf
sd
45
789
sdf
asdfl,sdf.sdfl,asdf
......asdfkl
las
Process finished with exit code 0

Remove the comment line and use a space or comma or period as a delimiter. The output is as follows:

123
asdf
sd
45
789
sdf
asdfl
sdf
sdfl
asdf
asdfkl
las
Process finished with exit code 0

4. API is relatively practical

The following are relatively practical:

delimiter()

Returns the Pattern that this Scanner is currently being used to match the delimiter.

hasNext()

Determines whether the next segment exists after the current scan position in the scanner. (The original APIDoc comment is ridiculous)

hasNextLine()

Returns true if another line exists in the input to this scanner.

next()

Finds and returns the next complete tag from this scanner.

nextLine()

This scanner executes the current line and returns the skipped input.


Related articles: