Reputation: 8384
I'm new to Java and I'm not sure if I even ask this question right. I have two voids, in the second one I get my string and I want to use it my main void. The code is something like that:
public void onCreate(Bundle savedInstanceState) {
shuffle();
//Here I want to use the string correctAnswer
}
public void shuffle() {
String correctAnswer = "whatever";
}
Upvotes: 0
Views: 235
Reputation: 7070
You will have to either return
the String
(no longer void method) or assign it to a string that has scope outside the method.
private String correctAnswer;
public void shuffle()
{
correctAnswer = "whatever";
}
Then you can use it in other methods in your class.
Upvotes: 3
Reputation: 10039
You could either declare a global like -
String correctAnswer = "";
public void onCreate(Bundle savedInstanceState) {
shuffle();
//Use it here
}
public void shuffle() {
correctAnswer = "whatever";
}
But remember onCreate() will be called first, so it would be better to return a String with shuffle() like -
public void onCreate(Bundle savedInstanceState) {
shuffle();
System.out.print(shuffle());
}
public String shuffle() {
correctAnswer = "whatever";
return correctAnswer;
}
Upvotes: 1
Reputation: 50538
You must return it if you have used that string locally. Change the method type to String
add return statement return CorrectAnswer
;
then in your main call this method something like:
String answer = shuffle();
Upvotes: 0
Reputation: 11308
If you want to use the String calculated in the second function, why use void?
public void onCreate(Bundle savedInstanceState) {
String s = shuffle();
//Use s;
}
public String shuffle() {
String correctAnswer = "whatever";
return correctAnswer;
}
You could also make correctAnswer an instance variable:
private String correctAnswer;
public void onCreate(Bundle savedInstanceState) {
shuffle();
//Use instance variable correctAnswer;
}
public void shuffle() {
correctAnswer = "whatever";
}
Upvotes: 6