java - 如何使函数添加到 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
所以基本上在我再次运行第一个菜单选项之后,它只是用新输入替换字符串。我怎样才能将它添加到字符串的末尾?
解决方案
所以在主类中执行此操作并替换_userInput
为userInput
.
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;
}
无论字符串是否为空,它都会做同样的事情。
推荐阅读
- azure - 从 LAN 创建类似云的 Azure?
- mysql - 如何将SQL表中的一列从短文本修改为长文本
- java - 用于查找最高元素的并行数组
- selenium - 使用 selenium 执行脚本时出错
- arrays - 在 Swift 中,如何检查数组的第一个元素是否等于值列表?
- javascript - 如何制作“身份”源图
- javascript - 如何将 XMLHttpRequest 的 setRequestHeader 读取到我的 API?
- powerbi - 循环遍历 power bi 中的可视化
- javascript - 使用 axios 时从服务器获取 json 错误响应
- c# - 从在 FormView 中绑定数据的 DropDownList 中删除重复项