我不确定我在这个特定代码中哪里出了问题。有人能给我一些指导吗?
这是我的问题,以及我试图得到的结果。
修改songVerse来玩“名字游戏”(OxfordDictionaries.com),将"( Name )“替换为userName,但不带第一个字母。
例如:如果userName = "Katie“和songVerse = "Banana-fana fo-f(Name)!",程序会打印: Banana-fana fo-fo-fo!例如:如果userName = "Katie“和songVerse = "Fee fi mo-m(Name)",程序输出: Fee fi mo-matie注意:您可以假设songVerse总是包含子字符串"(Name)”。
我最后一次尝试的代码,time...and,不管我放入什么,我总是得到相同的结果。我尝试了"userName.substring()“的不同场景,但仍然有相同的结果。
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse + userName.substring(1 , userName.length()); // this is where my problem is.
System.out.println(songVerse);
}
}
1测试通过
所有测试均已通过
Run
Testing Katie and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!tie
Expected output
Banana-fana fo-fatie!
Testing Walter and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!lter
Expected output
Banana-fana fo-falter!
Testing Katie and Fee fi mo-m(Name)
Output differs. See highlights below.
Your output
Fee fi mo-m(Name)tie
Expected output
Fee fi mo-matie
发布于 2019-09-09 16:45:47
这就是你要的。
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName.substring(0));
System.out.println(songVerse);
}}
发布于 2018-10-08 02:29:06
在这里,您已经从userName中删除了第一个字符,所以在倒数第二行时,您不需要再删除它。对于歌曲Verse,您需要删除其中的"(NAME)“,所以在这里您可以使用
songVerse = songVerse.replace("(NAME)","");
songVerse = songVerse+userName;
发布于 2018-10-08 05:27:02
方法substring(int begin,int end)让我们从初始字符串开始选择/创建一个子字符串,指示该子字符串应该开始、结束或仅从其开始的字符数。没有其他变体可以编辑子字符串,而它不会成为新生成的字符串的一部分(在您的示例中为“string songVerse”)。object.replace()方法应该将所指示的“文本”(在本例中是“(Name)”)更改为您想要插入的任何内容,而不是独立于“Text”之前或之后的字符的数量或类型。Nicholas K提出的变体是正确的,应该可以工作,或者您可以尝试其较短的版本,但结果将是相同的:
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
songVerse = scnr.nextLine();
songVerse = songVerse.replace("(Name)", userName.substring(1));
System.out.println(songVerse);
}
}
https://stackoverflow.com/questions/52691492
复制相似问题