toString 方法不将字母大写

toString method Not Capitalizing Letters

我正在学习 Java class,我需要做的一项作业是在我的代码中实现字符串方法。在提示用户设置文本后,我使用了 toLowerCase() 方法并打印了它。在另一行中,我使用了 toUpperCase() 方法并将其打印出来。两者都打印正确,但每当我使用 toString() 方法时,它只是我的小写文本。

这是我的主要内容class:

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);

    }
}

这是我的class和我所有的方法

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()
    {
        text = text.toUpperCase();
        return text;
    }

    // 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()
    {
        text = text.toLowerCase();
        return text;
    }

    // Reset the instance variable to the new text
    public void setText(String newText)
    {
        text = newText;
    }

    // Returns a String representatin 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()
    {
        text = text;
        return "I say, " + "\"" + text + "\"";
    }
}

对于冗长的粘贴和我糟糕的英语,我深表歉意。

是因为你修改了text的值。即使在您 return 之后,它也会持续存在。你不应该。相反,直接 return 像这样:

String yell() {
    return text.toUpperCase();
}

使用您的方法 yell()whisper,您还可以编辑变量 text。事实上,在行

之前
    System.out.println(talky);

您使用了whisper方法将变量text变为小写。

您必须像这样编辑您的代码:

public String whisper()
    {
        return text.toLowerCase();
    }

public String yell()
    {
        return text.toUpperCase();
    }

public String toString()
    {
        return "I say, " + "\"" + text + "\"";
    }

而且,更准确的说,在使用变量text的同时使用Javakeywordthis!例如,

public Talker(String startingText)
    {
        this.text = startingText;
    }