My professor performs the following tasks to get the user from:
scanner scanner = New scanner (System.in); Integer.parseInt (scanner.nextLine ());
Just scanner.nextInt ()
?
What are the benefits to doing java.util.Scanner.java?
contains the following:
public int nextInt () {next next (defaultRadix); } Public int nextInt (int radix) {// Check cached result if ((type cache! = Null) & amp; amp; amp; amp; amp; amp; amp; amp; amp ; This.radix == radius) {int val = ((integer) typeCache) .intValue (); UseTypeCache (); Return valve; } Setredics (radix); ClearCaches (); // search for the next int try {string s = next (integer pattern); If (matcher.group (SIMPLE_GROUP_INDEX) == faucet) s = processIntegerToken (s); Return integer. Paracet (S, Radix); } Hold (numerate expiration nfe) {status = matcher.start (); // Do not leave bad tokens new input miss exception (nfe.getMessage ()); }}
As I have seen it, scanner
call integer.Apresent () itself, at the top of the extra focus pocus Is the only integer Have significant performance advantages in ParseInt (scanner.nextLine ())
? On the other hand, are there any drawbacks?
How to do data scanning through a file with significant file, and not user input?
-
myScannerInstance.nextInt Using ()
leaves a new line behind the character, therefore, if you have a call tonextInt ()
afternextLine ()
, Then thenextLine ()
will read the new line character instead of the actual information. Therefore, you have to load the word nextInt () after a newnextLine ()
which is a new line character hang .Next line ()
Do not leave behind a new line character
Code:
int age = myScannerInstance.nextInt () ; String name = myScannerInstance.nextLine (); // The real name here will not be read. The character of the new line will be read.
-
nextInt ()
will be read by going back to the built-in stream again Take the IO call time (expensive) to get this next integer There will be a lot of checks for.Next line ()
will only perform those checks. Therefore, if you callnextLine ()
once and read 5 integers (a line string ), Divide them and parse them as integers (usingInteger.parseInt ()), it will be faster and more efficient than each individual reading.
When you are running a very large loop, you will get a lot of performance benefit by using
nextLine ()
+parseInt ()
.Usage:
Using
nextInt ()
gives you an additional advantage in which you will get an exception if the input text is not an integer example123
is accepted ..123sdsa
throws aInputMismatchException
. So, you can grab it and handle it properly. Using the, the next line ()
will read the entire line, so, this will be the whole stringsada1231
and thenNumberFormatException
Can fail with that, if it can not parse the string as a number, you have to handle that exception.Normally, a
nextLine ()
/nextInt ()
call does not matter if you have a loop or if you have a lot If reading data, thenwill be very efficient with
readLine ()
withparseInt ()
.
Comments
Post a Comment