DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. Registered User
Join Date
Oct 2004
Posts
11

java problem

[code]
Hi!
I have a vector ( int []v={4,13,6,2}
I try to print out the smallest number(2). After compiling I get this messege: Arrays index is out of bound Exception.
I try also to print out the vector like this:2,4,6,13.
How do I solve these problems.
------------------------------------------------------

class MyVector{
public static void main(String[]args){
int smallest=Integer.MAX_VALUE;
int last;
int current;
int []v={4,13,6,2};
int i=0;
while(i>=0){
current= v[i+1];
last= v[ i ];

if(current>last){
smallest=last;
}else{
smallest=current;
}
i++;
}
System.out.println(smallest);
}
}

[code]

2. Registered User
Join Date
Jan 2005
Posts
45
What is your loop exit condition ?

You actually run an infinite loop : i is set to 0 then it is constantly increased whereas your exit condition is i>=0. This condition is always true. Consequently, the compiler complains once i reached the 3 value (according to your array, the last valid index is 3 but the first line inside the loop try to acess to the i+1 index).

Hope that could be useful,

3. Registered User
Join Date
Jan 2005
Posts
45
oops
You actually run an infinite loop : i is set to 0 then it is constantly increased whereas your loop condition is i>=0

4. Registered User
Join Date
Dec 2004
Location
Norway
Posts
14
And you don't have a Vector, you have an array.
The way to find the smallest in an int array is this:

Code:
```    int [] array=new int [] {1,3,8,5,0,9,7};
int smallest=Integer.MAX_VALUE;
for (int i=0;i<array.length;i++)
smallest=(smallest<array[i]) ? smallest : array[i];```
Or you could do an ascending sort an pick the first in the list
afterwards

Posting Permissions

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

 FAQ Latest Articles Java .NET XML Database Enterprise