When I try to run this code below and I enter any number I get this error - Exception in thread "main" java.lang.NumberFormatException: For input string: ""
How can this be resolved?
When I try to run this code below and I enter any number I get this error - Exception in thread "main" java.lang.NumberFormatException: For input string: ""
How can this be resolved?
Try with
int n = scanner.nextInt();
instead of
int n = Integer.parseInt(scanner.nextLine());
@develo is partially right by suggesting the use of scanner.nextInt()
though if you do that you will also need to remove the calls to Integer.parseInt
(.nextInt()
will return an int
, so no need to parse it into an Integer
)
However, the core problem with your code is the loop. You loop starts from 0 and you are looping 1 too many times like this:
for (int i = 0; i <= n; i++ ) {
Change it to either for (int i = 0; i < n; i++ ) {
or for (int i = 1; i <= n; i++ ) {
and it will work fine.
Is this a college or university task by any chance? :) (my son is doing a CS degree and this type of code looks familiar :) )
Also, java convention is that classnames always start with a capital letter - so your classname should be SumOfNumbers
with a filename of SumOfNumbers.java