我正在为一个类学习Java,我需要做的一项工作是在代码中实现String方法。提示用户设置文本后,我使用了toLowerCase()方法并进行了打印。在另一行,我使用了toUpperCase()方法并打印了它。两者都可以正确打印,但是每当我使用toString()方法时,它只会以小写形式显示我的文本。
这是我的主要班级:
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);
}
}
这是我所有的方法都在我的课上
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 + "\"";
}
}
我为冗长的粘贴和不愉快的英语表示歉意。
使用方法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 + "\"";
}
此外,更精确地说,当使用变量keyword时,请使用Javathis
text
!例如,
public Talker(String startingText)
{
this.text = startingText;
}
这是因为您修改了text
的值。即使您返回,它也将持续存在。你不应该。而是直接像这样返回:
String yell() {
return text.toUpperCase();
}