有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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(),以及其他表示我要删除的是磅符号的方式,但仍然会得到“此处找不到磅符号”打印出来

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

提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    JAVA中的Strings是不可变的。您正在替换,但从未将结果分配回words[budgetcount]

    更改代码中的以下行

    words[budgetcount] = words[budgetcount].replace("\u00A3", "");
    

    下面是另一种方法,使用Character.isDigit(...)识别一个数字,并编织一个仅数字字符串,该字符串稍后可以解析为整数

    代码片段:

    private String removePoundSign(final String input) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (Character.isDigit(ch)) {
                builder.append(ch);
            }
        }
        return builder.toString();
    }
    

    输入:

    System.out.println(removePoundSign("£12345"));
    

    输出:

    12345
    
  2. # 2 楼答案

    您还可以使用String.replaceAll方法

    代码段:

    public class TestClass {
    
        public static void main(String[] args){
    
            //Code to remove non-digit number
            String budgetCount = "£34556734";
            String number=budgetCount.replaceAll("[\\D]", "");
            System.out.println(number);
    
            //Code to remove any specific characters
            String special = "$4351&2.";
            String result = special.replaceAll("[$+.^&]",""); // regex pattern
            System.out.println(result);
    
        }
    }
    

    输出:

    34556734
    43512