Thursday, July 9, 2009

Beginning java and strings?

so i got my midterm back i completely do not understand these 3 questions. if somebody could help with one or all that would be awesome...





you will use this as reference to the questions:





public class Special String


{


....public int countChar(char c) {....}


....public static int countArrayOfChar(char c, SpecialString strings[]) {...}


}





1. Call the countChars method ont he letter 's' on the last SpecialString of the array. (I initialized it as SpecialString array[]={"5j", "is", "fun"} )Place the result in a variable named num.


this is what i think it should be: int num= array[2].countChars('s');


(is this right? do i need 's' or just s?)


.


2. Call the countArrayOfChar method on the letter 'f' on the entire array


i put: array[ ].countArrayOfChar(f, array)


.


3. Change the value of the string "is" to "is loads of"


i thought it would just be: s[1]= "is loads of"; but i guess that wasn't right?


.


my final is weds. so i'm trying to figure out what i did wrong so do it right on the final

Beginning java and strings?
1) You do need single quotes around the s, otherwise the compiler will assume it is to pass the variable s. The other thing that the instructor might have been looking for was not hard coding the element number in your call to countChar(). Using the length method, you can determine the number of elements and use that instead of [2]. This way if your programme was initialised with a fourth or fifth string, or the strings were read from 'the outside' it would still work. Something like this would work:





n = array.length - 1; // remember arrays are zero based


array[n].countChars( 's' );





2) The countArrayOfChar() method is a static method that accepts an array of special strings as a parameter. So, you must invoke it this way:





SpecialString.countArrayOfChar( 'f', array );





3) I believe that you need


array [1] = new SpecialString( "is loads of" );





because you are allocating a new special string, not a regular string, to replace the special string "is".





Best of luck on your final!
Reply:I find this a bit confusing and I'm not convinced these are correct, but I'll try:





SpecialString [] array = {"5j", "is", "fun};





1) //I can't figure this one out





2) SpecialString.countArrayOfChar(f, array); //countArrayOfChar is a static function





3) array[1] = "is loads of"; //not s[1] = "is loads of";








P.S. This question is harder/more confusing than the questions on the Sun Java Certification test


No comments:

Post a Comment