Scanner and Array

How to pass Scanner.nextInt() to Array

Page 1 of 1

3 Replies - 5239 Views - Last Post: 13 October 2010 - 06:35 PM Rate Topic: -----

#1 taingmeng  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • 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
Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

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

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Scanner and Array

Posted 13 October 2010 - 05:42 PM

Read a whole line using
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]
Was This Post Helpful? 1
  • +
  • -

#4 fearDman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1