Results 1 to 4 of 4
Thread: Need HELP with LetterCounter
- 09-20-2011, 01:50 AM #1
Member
- Join Date
- Sep 2011
- Posts
- 2
- Rep Power
- 0
Need HELP with LetterCounter
Hey guys, I need help with my homework. I'm super new to coding on my own as you can see and I need to create a character counter using an array, in just this one method.
So yeah, I'm stuck and I don't know what to do next. With only this code, the test for "" comes out as a pass but tests with actual strings come out as failed because the array entries are 0. And according to my notes, apparently I need an else statement after the if and I need to implement Characters.toLowerCase for some reason. Thanks a lot guys.Java Code:public int[] letterCounts(String s) { int count = 0; int[] array= new int [27]; for(int i= 0; i < s.length(); i++){ if(s.charAt(i)>=1);{ count++;{ } } } return array; } }
Oh and here's one of the tests
Java Code:@Test public void test02() { String s = "Baaa!"; LetterCounter lc = new LetterCounter(); int [] expected = new int[27]; expected[0] = 3; expected[1] = 1; expected[26] = 1; int [] actual = lc.letterCounts(s); String result = arraysAreTheSame(s,expected,actual); assertTrue(result, result.length()==0); }
-
Re: Need HELP with LetterCounter
The best way to solve something like this is to first work out the algorithm, the steps required to solve the problem, and for this you don't even need a computer, but instead just a pen and paper. I suggest that you write out the steps that are required to solve something like this if *you* are the computer and had to solve this. Write out each step one on each line, no matter how trivial they seem. Then once done, you translate these steps into Java.
- 09-20-2011, 03:45 AM #3
Member
- Join Date
- Sep 2011
- Posts
- 2
- Rep Power
- 0
Re: Need HELP with LetterCounter
the translation is the hard part haha, what I'm confused about is how the array knows what to assign a-z to.
-
Re: Need HELP with LetterCounter
Some hints:
- You'll want to translate your String to all upper case or lower case before working on it, because I'm assuming that you're just interested in characters regardless of their case.
- a char can be cast to a number, an int, and used as such. If you create such a number and subtract (int)'a' from it (assuming you're working with lower case numbers), you'll get the 0-based ordinal number for the char, meaning 'a' - 'a' == 0, and 'b' - 'a' will == 1. You can use these numbers for your array index.
- You can get the value held by the array at position x, add 1 to it and then put the new number back into the array at the same position.
Have fun.


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks