# scope of varibles & conversion

Hi All,
I have a variable as shown below:
String curVal=request.getParameter("curVal");
// values are like -> only 4 (or)  only 4, 5 (or)  only  4,  5,  6
so now I want to store this values in array, so lets think values in "curVal -> 4,  5,  6"
int items[] = new int[4];
java.util.StringTokenizer st = null;
if(curVal.length() > 0)
{
st = new java.util.StringTokenizer(curVal,",");
}
int j;
for(j=0;j<4;j++)
{
while(st.hasMoreTokens())
{
items[j]= Integer.parseInt(st.nextToken());
System.out.println("array :"+items[j]);
}
}
// now I am expecting  4, 5,6,0 in array in the below statements, but I am getting 6,0,0,0 why?
System.out.println("array 0:"+items[0]);
System.out.println("array 1:"+items[1]);
System.out.println("array 2:"+items[2]);
System.out.println("array 3:"+items[3]);
%>

###### Who is Participating?

Commented:
Take a look at this example:

output:
array :4
array :5
array :6
array 0:4
array 1:5
array 2:6
array 3:0
``````public class SampleStringTest {
public static void main(String args[]){
//String curVal=request.getParameter("curVal");
String curVal = "4,5,6";
//		 values are like -> only 4 (or)  only 4, 5 (or)  only  4,  5,  6
//so now I want to store this values in array, so lets think values in "curVal -> 4,  5,  6"
int items[] = new int[4];
java.util.StringTokenizer st = null;
if(curVal.length() > 0)
{
st = new java.util.StringTokenizer(curVal,",");
}
int j=0;

while(st.hasMoreTokens())
{
items[j]= Integer.parseInt(st.nextToken());
System.out.println("array :"+items[j]);
j++;
}

// now I am expecting  4, 5,6,0 in array in the below statements, but I am getting 6,0,0,0 why?
System.out.println("array 0:"+items[0]);
System.out.println("array 1:"+items[1]);
System.out.println("array 2:"+items[2]);
System.out.println("array 3:"+items[3]);
}
}
``````
0

Commented:
0

Commented:
Here you messed up the code.

for(j=0;j<4;j++)
{
while(st.hasMoreTokens())
{
items[j]= Integer.parseInt(st.nextToken());
System.out.println("array :"+items[j]);
}
}
0

Commented:
Your code is messed up because you are looping again using the for loop.  You have alread used while(st.hasMoreTokens) to loop thru all the tokens and you actually stored everything in the
items[0] element only.
while(st.hasMoreTokens())
{
items[j]= Integer.parseInt(st.nextToken());
System.out.println("array :"+items[j]);    ---------------> Print j also here. Then you will understand.

}

And then again looped the array again using for loop.

So look at my code, I simply removed the for loop and stored the elements in items[0] to items[2] using the while loop and by incrementing 'j' each time.

Ask me more if you don't understand the explanation :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.