How do I access indexes?

Discussion in 'Programming General' started by kmjt, Jan 22, 2012.

How do I access indexes?
  1. Unread #1 - Jan 22, 2012 at 1:49 AM
  2. kmjt
    Joined:
    Aug 21, 2009
    Posts:
    14,450
    Referrals:
    8
    Sythe Gold:
    449

    kmjt -.- The nocturnal life chose me -.-
    Banned

    How do I access indexes?

    For a question i'm supposed to get the user to enter a string then count the number of consonants, vowels, numbers and "other" characters in the string.

    So first we would get the length of the string. I know how to do that.

    Next I made variables for consonants, vowels and numbers and set them all equal to 0. Then I set a variable called "index" equal to 0. My plan is to make a loop that will go over every single character in the string and if it is a vowel, vowel++, if it is a number, number++ and so forth. After checking an index I will index++. Once the first index of the string is looked over, the next index is looked over assuming the index is less than or equal to the length of the string.

    My problem is I don't know how to access an index. I was thinking

    char c = characters.charAt(index);

    and then another nested loop where if c is a vowel, etc. it will be added to the vowel counter or the appropriate counter. So after this loop plays the first time for example, index will be set to 1 from 0 and then the 2nd character will be checked. This goes on until all of the characters in the string are looked at.

    But how do I do this? How do I access a certain index?

    I have some code done but I don't want to post it because it is for a school assignment.
     
  3. Unread #2 - Jan 22, 2012 at 8:56 AM
  4. Nullware
    Joined:
    Jan 30, 2007
    Posts:
    1,761
    Referrals:
    4
    Sythe Gold:
    0

    Nullware Guru

    How do I access indexes?

    Hey you seem to be on right track and you are correct about how to get a character from the string.

    So if you are looping through the string and getting characters.charAt(index) in each iteration all you have to do is check what that character is using if statements. You don't need a nested loop so it will just look something like this.

    Code:
    for(index = 0; index < string.length; index++)
       if(consonant)
       else if(vowel)
       else if(number)
       else
     
  5. Unread #3 - Jan 24, 2012 at 5:47 AM
  6. kmjt
    Joined:
    Aug 21, 2009
    Posts:
    14,450
    Referrals:
    8
    Sythe Gold:
    449

    kmjt -.- The nocturnal life chose me -.-
    Banned

    How do I access indexes?

    Thanks that was very helpful. I completed the problem, this can be closed.
     
< Wanting to learn HTML | Help With JAVA Work Sheet (Recursion) >

Users viewing this thread
1 guest


 
 
Adblock breaks this site