Results 1 to 3 of 3
- 02-04-2013, 11:03 PM #1
Member
- Join Date
- Feb 2013
- Posts
- 5
- Rep Power
- 0
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?
- 02-04-2013, 11:12 PM #2
Senior Member
- Join Date
- Feb 2009
- Posts
- 312
- Rep Power
- 11
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];
- 02-04-2013, 11:47 PM #3
Member
- Join Date
- Feb 2013
- Posts
- 5
- Rep Power
- 0
Similar Threads
-
need to input values from a text file into an array and count values
By pds8475 in forum New To JavaReplies: 14Last Post: 01-22-2011, 03:36 PM -
Loop through array and check values...
By Spinalkord in forum New To JavaReplies: 1Last Post: 10-24-2010, 11:17 AM -
reading values into variables using java
By kskgupta in forum New To JavaReplies: 2Last Post: 05-16-2010, 06:48 AM -
[SOLVED] Debug: values not shown for variables
By jwilley44 in forum EclipseReplies: 7Last Post: 01-30-2009, 04:33 AM -
how to have function variables remember their values between calls
By asterik123 in forum New To JavaReplies: 2Last Post: 08-03-2007, 05:06 PM
Bookmarks