Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

hasNextInt()

EPPHO
 Share

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?

Link to comment
Share on other sites

Link to post
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()

 

Link to comment
Share on other sites

Link to post
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...

Link to comment
Share on other sites

Link to post
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

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share


×