首页 > 解决方案 > 如何使函数添加到 main 中的字符串而不替换字符串中的先前数据?

问题描述

我正在尝试制作菜单选项,其中选项 a 的功能将允许用户将数据输入到字符串中。当 a 被召回时,我无法在不删除先前的情况下将新用户输入到字符串中。我尝试使用 concat 添加到字符串的末尾,但它只是不断地用字符串中的新文本替换旧文本。以下是我的主要课程选项a。

for(;;)
        {
        menuOptions();
           String[] menuChoice = new String[4];
           menuChoice[0] = choice.next();
           System.out.println("your choice is " + menuChoice[0] + "\n");
        
        if (menuChoice[0].equals("a"))
        {//menu choice a.
            userInput = optionA(_userInput);
        }

以下是我对选项 a 的功能。

        public static String optionA(String _userInput)
        {
            _userInput = "";
            Scanner s = new Scanner(System.in); //Scanner for user input.
            System.out.println("Enter new text: ");
            if (_userInput == "") {//checks if string is empty
                _userInput = s.nextLine();
                System.out.println(_userInput);
            } else 
            {
            String newLine = s.nextLine();

            _userInput = _userInput.concat(newLine);
            }//end else
            return _userInput;

我的第二个菜单选项允许用户查看字符串中存储的内容。现在,当我运行选项 a 和 b 两次时,会发生以下情况:

option a 1st time: enter text: "All the way!"
option b 1st time: search: "All" output - index 0
option a 2nd time: enter text: "Even more!"
option b 2nd time: search: "All" output - index -1

所以基本上在我再次运行第一个菜单选项之后,它只是用新输入替换字符串。我怎样才能将它添加到字符串的末尾?

标签: javajava.util.scanner

解决方案


所以在主类中执行此操作并替换_userInputuserInput.

String userInput  = "";
Scanner s = new Scanner(System.in);
...
if (menuChoice[0].equals("a"))
        {
            userInput = optionA(userInput,s);
        }

对于选项A

public static String optionA(String userInput, Scanner s)
{
      System.out.println("Enter new text: ");
      String newLine = s.nextLine();
      userInput = userInput + newLine;
      return userInput;
}

无论字符串是否为空,它都会做同样的事情。


推荐阅读