java如何从数组对象中删除符号并保存?
我正在为一个大学项目编写一个基本聊天机器人。用户必须通过输入金额来设置预算。目前,该程序能够在用户消息中搜索数字并正确保存。但是,如果在其前面加上英镑符号,则由于消息中有英镑符号,因此无法将其另存为整数
这是我的代码:
//Scan the user message for a budget amount and save it.
for (int budgetcount = 0; budgetcount < words.length; budgetcount++)
{
if (words[budgetcount].matches(".*\\d+.*"))
{
if (words[budgetcount].matches("\\u00A3."))
{
words[budgetcount].replace("\u00A3", "");
System.out.println("Tried to replace a pound sign");
ResponsesDAO.budget = Integer.parseInt(words[budgetcount]);
}
else
{
System.out.println("Can't find a pound sign here.");
}
}
我以前试过。contains(),以及其他表示我要删除的是磅符号的方式,但仍然会得到“此处找不到磅符号”打印出来
如果有人能提供建议或纠正我的代码,我将不胜感激
提前谢谢
# 1 楼答案
JAVA中的
Strings
是不可变的。您正在替换,但从未将结果分配回words[budgetcount]
更改代码中的以下行
下面是另一种方法,使用
Character.isDigit(...)
识别一个数字,并编织一个仅数字字符串,该字符串稍后可以解析为整数代码片段:
输入:
输出:
# 2 楼答案
您还可以使用
String.replaceAll
方法代码段:
输出: