Results 1 to 2 of 2
  1. #1
    wizar is offline Member
    Join Date
    Nov 2010
    Posts
    18
    Rep Power
    0

    Default Scanner input into array

    I have inputs such as "1 2 3" being inputted into my program.
    I am using Scanner to look for the numbers. I would like to put these numbers into an array, but how would I initialize the array size if the inputs vary in size? For example, what if the input has more than 3 numbers?

    Here is the code I am working with:
    Java Code:
    Scanner scan = new Scanner(System.in);
        int [] array = new int [3];
        
        for (int i = 0; i < array.length; i++)
        {
          array[i] = scan.nextInt();
        }
        for (int z = 0; z< array.length; z++)
        {
          System.out.print(array[z] + " ");
        }

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default Re: Scanner input into array

    3 options:

    1 - ask user how many numbers they are entering and then create an array with that size.

    2 - create an array of some length. Keep track of how many numbers have been entered. When the array is full create a new bigger array. Copy values from old array to new array. Insert new value.

    3 - use a List.

Similar Threads

  1. Converting Scanner input to JOptionPane
    By Mideoan in forum New To Java
    Replies: 1
    Last Post: 03-10-2011, 12:26 AM
  2. End Scanner int input with text value
    By BillyB in forum New To Java
    Replies: 3
    Last Post: 03-07-2011, 06:13 PM
  3. how to reverse some input from scanner
    By moncur in forum New To Java
    Replies: 24
    Last Post: 11-09-2010, 03:59 PM
  4. Changing Scanner input type
    By mlad in forum New To Java
    Replies: 13
    Last Post: 03-18-2010, 05:22 PM
  5. Scanner input problem
    By slayer_azure in forum New To Java
    Replies: 3
    Last Post: 05-26-2008, 11:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •