Reputation: 39
I'm attempting to code my first Android App for a friend, and the basic function is to display a random quote from one of three characters when a button is clicked. (Sorry for the poor terminology.)
The issue I'm having is in returning a quote chosen at random out of an array after having accessed that array with another randomly generated number and if/else if terms.
I have one package that I'm hoping to access from the Main Activity using
String quote = mDoctorWho.getDoctorQuote;
That package has my if/else if statements in it here:
private Nine mNine = new Nine();
private Ten mTen = new Ten();
private Eleven mEleven = new Eleven();
public String getDoctorQuote() {
// Choose a Random number out of three values
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(3);
// Use that value to choose which of the Doctors to get a quote from
if (randomNumber == 0) {
// Quote from Nine
String quote = mNine.getQuote();
}
else if (randomNumber == 1) {
// Quote from Ten
String quote = mTen.getQuote();
}
else if (randomNumber == 2) {
// Quote from Eleven
String quote = mEleven.getQuote();
}
else {
String quote = "Error";
}
return quote;
}
The last line above, to return quote, is the one getting the error 'quote cannot be resolved into a variable'.
mNine, mTen, and mEleven are all nearly-identical packages that look about like this:
public String[] mElevenQuotes = {
"Quote here",
"Quote here",
"Quote here" };
public String getQuote() {
String quote = "";
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mElevenQuotes.length);
quote = mElevenQuotes[randomNumber];
return quote;
}
(I removed the quotes so that they wouldn't take up room - I wasn't sure whether this package of code would be useful or not.)
I've looked for a solution and have tried figuring out a problem with the scope, but haven't found a fix. How can I return the quote to the main activity after having it choose a random character, and then a random quote from that character?
Upvotes: 1
Views: 677
Reputation: 54672
you are declaring the quote
variaable within if blocks. so outside the blocks there is no existence. Do something like this
public String getDoctorQuote() {
String quote = ""; // declare the variable before
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(3);
// Use that value to choose which of the Doctors to get a quote from
if (randomNumber == 0) {
// Quote from Nine
quote = mNine.getQuote();
}
else if (randomNumber == 1) {
// Quote from Ten
quote = mTen.getQuote();
}
else if (randomNumber == 2) {
// Quote from Eleven
quote = mEleven.getQuote();
}
else {
quote = "Error";
}
return quote;
}
Upvotes: 2