Results 1 to 4 of 4
  1. #1
    slidepuppy1 is offline Member
    Join Date
    Oct 2011
    Posts
    2
    Rep Power
    0

    Default How to get the value of an index

    My code is:

    public int indexOfFile(String filename) {
    int indexOfFile=0;
    for(int i=0; i<DRIVE_SIZE; i++) {
    indexOfFile=0;
    if(drive[i]!=null && drive[i].getName().equals(filename)) {
    indexOfFile= i;
    }else{
    indexOfFile=-1;
    }
    }
    return indexOfFile;
    }

    I want it to either return the value of i or -1, but all this does is returns -1. Can anyone tell me where I'm going wrong?

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default Re: How to get the value of an index

    if the if-statement is true, you set the variable to i but the loop continues. in the next iteration, the condition no longer applies and you set the variable to -1
    Last edited by eRaaaa; 11-06-2011 at 10:49 PM.

  3. #3
    slidepuppy1 is offline Member
    Join Date
    Oct 2011
    Posts
    2
    Rep Power
    0

    Default Re: How to get the value of an index

    But how do I fix that? I tried taking the -1 out of the loop so I have:


    public int indexOfFile(String filename) {
    int indexOfFile=0;
    for(int i=0; i<DRIVE_SIZE; i++) {
    indexOfFile=0;
    if(drive[i]!=null && drive[i].getName().equals(filename)) {
    return i;
    }
    }
    return -1;
    }

    but it still returns -1

  4. #4
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default Re: How to get the value of an index

    have you checked that your condition is true?
    (System.out oder debug your code!) Maybe you have invisible characters so equals doestn match ?!

Similar Threads

  1. Convert Map to Index
    By alpdog14 in forum New To Java
    Replies: 2
    Last Post: 03-29-2011, 08:03 PM
  2. Redirecting port 80 index to port 8080 index
    By chyrl in forum Advanced Java
    Replies: 0
    Last Post: 11-30-2010, 04:15 PM
  3. Replies: 0
    Last Post: 10-29-2010, 09:15 PM
  4. Index of an int
    By wake in forum New To Java
    Replies: 4
    Last Post: 02-24-2010, 02:54 PM
  5. I can't run my index.jsp
    By gissah in forum New To Java
    Replies: 0
    Last Post: 03-23-2009, 02:42 AM

Posting Permissions

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