# Scanner and Array

Page 1 of 1

## 3 Replies - 8258 Views - Last Post: 13 October 2010 - 06:35 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=194866&amp;s=cc8427b1b129bc587d306d04971b9358&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 taingmeng

Reputation: 0
• Posts: 1
• Joined: 11-October 10

# Scanner and Array

Posted 13 October 2010 - 05:33 PM

How to pass the values into Array by using Scanner to read a line of integers from user input without knowing how many integers the user inserts?

For example:

Input: 2 21 53 18 36

=>array[0]=2;
=>array[1]=21;
=>array[2]=53;
=>array[3]=18;
=>array[4]=36;

Input: 34 21 58 65 97 ... n

=>array[0]=34;
=>array[1]=21;
=>array[2]=58;
=>array[3]=65;
=>array[4]=97;
=>...........;
=>array[n-1]=n;

Is This A Good Question/Topic? 0

## Replies To: Scanner and Array

### #2 n8wxs

• --... ...-- -.. . -. ---.. .-- -..- ...

Reputation: 972
• Posts: 3,878
• Joined: 07-January 08

## Re: Scanner and Array

Posted 13 October 2010 - 05:40 PM

Split the input line into a string array. The length of the string array will tell you how many numbers the user entered

### #3 pbl

• There is nothing you can't do with a JTable

Reputation: 8362
• Posts: 31,955
• Joined: 06-March 08

## Re: Scanner and Array

Posted 13 October 2010 - 05:42 PM

String line = scan.nextLine();
use the String method split(" ") to get an array of String one element for each group of numbers
build an int[] array of that size
loop to your array of String calling the Integer.parseInt() method to translate all String[i] into int[i]

### #4 fearDman

Reputation: 0
• Posts: 3
• Joined: 01-October 10

## Re: Scanner and Array

Posted 13 October 2010 - 06:35 PM

Depending on how strict the requirements are (eg. College class, personal use), you might want to consider using an ArrayList. That way it doesn't matter how many numbers the user entered, this ArrayList doesn't need a size to be set up front.