DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 4 of 4

Thread: java problem

Hybrid View

  1. #1
    Join Date
    Oct 2004
    Posts
    11

    Arrow 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. #2
    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,
    Lionel Badiou
    CodeFutures -
    Java Code Generation

    http://www.codefutures.com



  3. #3
    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
    Lionel Badiou
    CodeFutures -
    Java Code Generation

    http://www.codefutures.com



  4. #4
    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
    Java Wreck

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links