I think that having scanner look at the variable as a string and converting the dollar value to an int while appending the first index is super inefficient.
Drawing conclusions from thinking is for philosophers, not engineers.
Here's your proposed efficient version:
import java.util.*;
class NextInt {
public static void main(String[] args) {
Scanner keyboardIn = new Scanner(System.in);
int downPayment;
for(int i=0; i<10000000; i++) {
downPayment = keyboardIn.nextInt();
}
}
}
Here's your proposed super inefficient version:
import java.util.*;
class AsString {
public static void main(String[] args) {
Scanner keyboardIn = new Scanner(System.in);
int downPayment;
for(int i=0; i<10000000; i++) {
String input = keyboardIn.next();
if (input.startsWith("$")) input = input.substring(1);
downPayment = Integer.parseInt(input);
}
}
}
We can generate 10 million lines of test data:
yes '1500' | head -n 10000000 > nodollar
yes '$500' | head -n 10000000 > dollar
Now benchmark it (best of 3):
$ time java NextInt < nodollar
real 0m3.544s
user 0m3.759s
sys 0m0.124s
$ time java AsString < dollar
real 0m2.530s
user 0m2.735s
sys 0m0.111s
As it turns out, not only are we talking about upper bound of ~0.4 microseconds saved time per user input, but you are spending your time and effort on a slower implementation. No wonder they say that premature optimization is the root of all evil!
Anyways, that was a tangent that doesn't actually answer the question. Have you considered using skip
to skip an optional $
?
keyboardIn.skip("[$]?");
downPayment = keyboardIn.nextInt();