Badr Hari
Badr Hari

Reputation: 8384

Passing a string between voids

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

Answers (4)

RMT
RMT

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

Suchi
Suchi

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

Nikola Despotoski
Nikola Despotoski

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

Marcelo
Marcelo

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

Related Questions