如何从数组对象中删除 £ 符号并保存它?

我正在为一个大学项目编写一个基本的聊天机器人。我到了用户必须通过输入金额来设置预算的地步。目前,该程序能够在用户的消息中搜索数字并正确保存。但是,当 £ 符号作为前缀时,由于邮件中包含井号,因此无法保存为整数。


这是我的代码:


//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()和其他指示它是我要删除的磅符号的方法,但我仍然得到“在这里找不到磅符号”打印出来。


如果有人可以提供建议或纠正我的代码,我将不胜感激。


开心每一天1111
浏览 141回答 2
2回答

人到中年有点甜

Strings在JAVA中是不可变的。您正在替换,但从未将结果重新分配给 。words[budgetcount]更改代码中的以下行,words[budgetcount] = words[budgetcount].replace("\u00A3", "");这是另一种方法,通过使用来识别数字并编织一个仅数字字符串,该字符串以后可以解析为整数,Character.isDigit(...)代码段:private String removePoundSign(final String input) {&nbsp; &nbsp; StringBuilder builder = new StringBuilder();&nbsp; &nbsp; for (int i = 0; i < input.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; char ch = input.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; if (Character.isDigit(ch)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; builder.append(ch);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return builder.toString();}输入:System.out.println(removePoundSign("£12345"));输出:12345

有只小跳蛙

您也可以使用方法。String.replaceAll代码片段:public class TestClass {&nbsp; &nbsp; public static void main(String[] args){&nbsp; &nbsp; &nbsp; &nbsp; //Code to remove non-digit number&nbsp; &nbsp; &nbsp; &nbsp; String budgetCount = "£34556734";&nbsp; &nbsp; &nbsp; &nbsp; String number=budgetCount.replaceAll("[\\D]", "");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(number);&nbsp; &nbsp; &nbsp; &nbsp; //Code to remove any specific characters&nbsp; &nbsp; &nbsp; &nbsp; String special = "$4351&2.";&nbsp; &nbsp; &nbsp; &nbsp; String result = special.replaceAll("[$+.^&]",""); // regex pattern&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(result);&nbsp; &nbsp; }}输出:3455673443512
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java