• Log in or sign up for an account here: https://www.sythe.org/login

How do I access indexes?

kmjt

-.- The nocturnal life chose me -.-

Banned
Joined
Aug 21, 2009
Sythe Gold
449
Messages
14,450
Location
Canada
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.
 
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
 
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

Thanks that was very helpful. I completed the problem, this can be closed.
 
Runescape Gamblingrunescape gambling
Back
Top