我需要一些关于 JAVA 中子字符串函数的指导

我不确定这个特定代码哪里出了问题。有人可以给我一些指导吗?


这是我的问题以及我试图作为结果的结果。


修改 songVerse 以播放“The Name Game”(OxfordDictionaries.com),将“(Name)”替换为 userName 但没有首字母。


例如:如果 userName = "Katie" 和 songVerse = "Banana-fana fo-f(Name)!",程序打印:Banana-fana fo-fatie!例如:如果 userName = "Katie" 和 songVerse = "Fee fi mo-m(Name)",程序将打印: Fee fi mo-matie 注意:您可能认为 songVerse 将始终包含子字符串“(Name)”。


我上次尝试过的代码......无论我输入什么,我都会得到相同的结果。我尝试了“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);

    }

}


弑天下
浏览 142回答 3
3回答

哆啦的时光机

干得好。  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);} }

哔哔one

您的代码的问题在于您没有尝试解决您在问题中描述的问题。尝试执行以下步骤:设计一份用英文写的解决问题的步骤清单;注意细节。手动运行步骤 1 中的步骤列表。将步骤 1 中的步骤转换为代码。这里有一些提示:您将一次阅读一行歌词。有些线路有替代品,有些则没有。您将收到 Name 作为输入一次;生成名称替换值一次并在每次执行替换时使用它。你的代码很糟糕。这里有更多关于“注意细节”的内容您的代码中没有循环;这将读取一行歌词并执行一次替换。计算歌词中的行数。如果行数大于 1,那么您的技术肯定会失败。如果您的代码中有一个循环但决定不将其包含在您的代码中,请停止在您的问题中撒谎。我们无法帮助您修复您假装不存在的代码。在一个理智的世界中,用于替换的名称只会出现一次。读一遍。为了替换字符串中的 (Name),您必须首先在字符串中找到 (Name)。

胡子哥哥

这很容易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.replace("(Name)", userName);  /* Your solution goes here  */  System.out.println(songVerse);  }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java