Answered
Mike suggested I added some code to the
default:
break;
part of the switch. I added an exception to it, and there is no need to change anything else. The code now runs successfully. Thanks guys!
EDITED FOR READABILITY:
Error: “Description Resource Path Location Type
The local variable messages may not have been initialized TweetFragment.java /Offline Twitter/src/com/deadpixels/offline/twitter line 78 Java Problem”
for line:
int handleStartsAt = messages[i].indexOf('@');
And the same error happens twice on line 80, that being:
ph = messages[i].substring(handleStartsAt, messages[i].length());
As far as your questions, the
default:
break;
line was added as the int tweet type should only be either 0, 1, or 2. The function is called within a controlled environment and that way I am sure the call will not return an exception.
END OF EDIT.
I am trying to create a method to return a String array. This String array has a size that will change depending on the message type that is passed to the method as a parameter. I am having some issues getting this done, as apparently I am not initializing my variable; although, I think I am.
The variable I am having issues with is the “messages” array.
Bear in mind that I cannot declare the following:
String [] messages = new String [arrayLength];
As at this point in the call I do not know the length of the array. And I cannot do this:
String [] messages = null;
since after this, I will run into a runtime error, despite of not getting alerts at compile time.
Also, just to clarify, I would have though that:
messages = OfflineTwitter.mentions;
the above line would be initializing the variable, “OfflineTwitter.mentions” is an array, only stored in a different class.
Here is the code snippet.
public String[] getHandles (int tweetType) {
int arrayLength = 0;
String [] handles;
String [] messages;
switch (tweetType) {
case 0:
arrayLength = OfflineTwitter.mentions.length;
messages = OfflineTwitter.mentions;
break;
case 1:
arrayLength = OfflineTwitter.directMessages.length;
messages = OfflineTwitter.directMessages;
break;
case 2:
arrayLength = OfflineTwitter.allTweets.length;
messages = OfflineTwitter.allTweets;
default:
break;
}
handles = new String [arrayLength];
for (int i = 0; i < arrayLength; i++) {
int handleStartsAt = messages[i].indexOf('@');
String ph = "";
ph = messages[i].substring(handleStartsAt, messages[i].length());
int handleEndsAt = ph.indexOf(":");
String sender = ph.substring(0, handleEndsAt);
handles[i] = sender;
}
return handles;
}
If
tweetType < 0 || tweetType > 2thenis reached which does not assign a value to
messages.You need to assign a value in the
defaultbranch, orthrowan exception, orreturnso that the array is initialized at first use.Perhaps change that to
or ideally change
tweetTypeto be anenumso that you can cover all cases exhaustively.and change
int tweetTypetoTweetType tweetType.