For example ....
26, 15, 37
How do I get a number from a scanner (for example, I want to add or subtract?)
If you want to use the scanner
API:
private static final pattern COMMA_PATTERN = pattern compile (" \\ s * , \\ s * "); Public listing & lt; Integer & gt; GetIntegerList () {// The hold scanner is located on the first integer in the list. & Lt; Integer & gt; Integers = new arreelist & lt; Integer & gt; (); For (;;) {integers.add (scanner.nextInt ()); Read (scanner.hasNext (COMMA_PATTERN)) {// and discard the comma token and continue the continue list. Scanner.next (); } Else {// number is not followed by a comma, stop parsing. break; }} Return integer; }
There is a need to deal with more errors, but hopefully, this example illustrates the approach.
You can also Scanner.useDelimiter ()
:
private static final pattern COMMA_PATTERN = Pattern.compile ("\\ s *, \\ S * "); Public listing & lt; Integer & gt; GetIntegerList () {// The hold scanner is located on the first integer in the list. & Lt; Integer & gt; Integers = new arreelist & lt; Integer & gt; (); Pattern old dalimeter = scannerdillimeter (); Scanner.useDelimiter (COMMA_PATTERN); While (scanner.hasNextInt ()) {integers.add (scanner.nextInt ()); } // Reset the delimiter scanner. Delimiter (old delimiter); Return integer; }
Comments
Post a Comment