Search In
• More options...
Find results that contain...
Find results in...

# hasNextInt()

Hello! How would you edit this code:

```while (sc.hasNextInt()) {
int x = sc.nextInt();
}```

for me to be able to access and print out first and last integer that user entered?

I know how to do this if I know how many integers user will enter,

but what if i don't know how many integers user will enter?

##### Share on other sites

Well, I imagine you would put the numbers in an array and you'd also store the amount of numbers read in a separate variable.

First number read would be array[ 0]  and last number read would be array [ amount of numbers read variable -1 because arrays start from 0]

I don't see any need to go through the whole array one by one ... or instead of using .NextInt()  whatever that means, create a .firstInt() and .lastInt()

##### Share on other sites

5 minutes ago, mariushm said:

Well, I imagine you would put the numbers in an array and you'd also store the amount of numbers read in a separate variable.

First number read would be array[ 0]  and last number read would be array [ amount of numbers read variable -1 because arrays start from 0]

I don't see any need to go through the whole array one by one ... or instead of using .NextInt()  whatever that means, create a .firstInt() and .lastInt()

How do you put numbers in an array if you don't know how many numbers user will enter? I thought you do it with code i pasted above...

##### Share on other sites

1 hour ago, frozeNNN said:

How do you put numbers in an array if you don't know how many numbers user will enter? I thought you do it with code i pasted above...

use a list instead of an array, then you can just keep adding to the list and check the first and last elements once you are done