Search code examples
javaresetinstance-variables

How would I reset the instance variable in this situation? I'm new to java so forgive me if it's a simple answer


No idea what anything is called but I'm pretty sure the one that runs the code is the main and that would be this one below this text. Also I'm using an online thing called codeHS so if it's not in the exact perfect format it won't accept what I do even if it works.

import java.util.Scanner;

public class TalkerTester
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter some text: ");
        String words = input.nextLine();
        
        
        Talker talky = new Talker(words); 
        String yelling = talky.yell();
        String whispers = talky.whisper();
        
        System.out.println(talky);
        System.out.println("Yelling: " + yelling);
        System.out.println("Whispering: " + whispers);
        
    }
}

And below this is the other part that does all the work, this is where the problem is. The above part was given to us beforehand so I'm not allowed to change it. If any other part is wrong let me know as well.

public class Talker
{
    private String text;
    
    // Constructor
    public Talker(String startingText)
    {
        text = startingText;
    }
    
    // Returns the text in all uppercase letters
    // Find a method in the JavaDocs that
    // will allow you to do this with just
    // one method call
    public String yell()
    {
        return text.toUpperCase();
    }
    
    // Returns the text in all lowercase letters
    // Find a method in the JavaDocs that
    // will allow you to do this with just
    // one method call
    public String whisper()
    {
        return text.toLowerCase();
    }
    
    // Reset the instance variable to the new text
    public void setText(String newText)
    {
        
    }
    
    // Returns a String representation of this object
    // The returned String should look like
    // 
    // I say, "text"
    // 
    // The quotes should appear in the String
    // text should be the value of the instance variable
    public String toString()
    {
        return "I say, \"" + text + "\"";
    }
}

Solution

  • // i am thinking you want to set the text to newText and this very much is borther.
    public void setText(String newText) {
         // By default a new string created and it is not the reference hope i
         // can what you want to say want anything else info please reply.
         this.text = newText;
    }