Search code examples
javamethodstostring

How can i call a String from a method in a toSting() method (all methods are in same class)


I've been stuck here for a while. I want to call string lesson from the lesson method into my toString() method. Both methods are in the same class.

Here is lesson method:

public static String lesson() {
    System.out.println("Now you have written about your day, what are the lesson learnt ? Huh??");
    Scanner lessonLearned = new Scanner(System.in);
    String lesson = lessonLearned.nextLine();
    return lesson;
}

Here is the toString method

@Override
public String toString() {
    String final = "";
    final = "[" + Calendar.getInstance().getTime() + "," +lessonShouldBeHere+ "," AnotherString  + "]";
    return out;
}

Solution

  • As written, String lesson is a local variable, and not accessible outside the context of the method (because it is on the stack and no longer exists).

    static String storedLesson = null;
    public static String lesson() {
        System.out.println("Now you have written about your day, what are the lesson learnt ? Huh??");
        Scanner lessonLearned = new Scanner(System.in);
        String lesson = lessonLearned.nextLine();
        storedLesson  = lesson;
        return lesson;
    }
    

    To solve this problem, make a static variable that holds the lesson value. I suggest static because this is a static method. If this method was a member method of a class, it would be better to make this a member variable.

    Then use storedLesson in your toString method