Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2013
    Posts
    5
    Rep Power
    0

    Default Trying to set various values into an array using variables and a loop

    I'm trying to set values in an array where the user can define the size of the array and inputs each value manually.

    My code for setting the values is:

    public void createArray()
    {
    if(arraySize > 0)
    {
    do{
    System.out.println( "Enter number "+ loop2);
    array = new int[arraySize];
    array[loop] = (int) scan.nextDouble();
    loop++;
    loop2++;
    }
    while (loop < arraySize);

    However, whenever I print out the results while running the program, the array will always only record the last number that was entered. For example, if I made the array hold 3 values, and I type in 1, 2, and 3, then after each value is entered it will return: 1,0,0, then 0,2,0, then 0,0,3. Anyone know what I'm doing wrong?

  2. #2
    StormyWaters is offline Senior Member
    Join Date
    Feb 2009
    Posts
    305
    Rep Power
    6

    Default Re: Trying to set various values into an array using variables and a loop

    The problem is that you are creating/assigning a new int[] instance every time this is being done:

    Java Code:
    array = new int[arraySize];
    Since this snippet is in the do-while loop, every iteration will create a new int[], and assign it to the "array" variable essentially wiping the previous information.

  3. #3
    Join Date
    Feb 2013
    Posts
    5
    Rep Power
    0

    Default Re: Trying to set various values into an array using variables and a loop

    Ah, of course. Thank you, this fixed the problem!

Similar Threads

  1. Replies: 14
    Last Post: 01-22-2011, 02:36 PM
  2. Loop through array and check values...
    By Spinalkord in forum New To Java
    Replies: 1
    Last Post: 10-24-2010, 10:17 AM
  3. reading values into variables using java
    By kskgupta in forum New To Java
    Replies: 2
    Last Post: 05-16-2010, 05:48 AM
  4. [SOLVED] Debug: values not shown for variables
    By jwilley44 in forum Eclipse
    Replies: 7
    Last Post: 01-30-2009, 03:33 AM
  5. Replies: 2
    Last Post: 08-03-2007, 04:06 PM

Tags for this Thread

Posting Permissions

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