有 Java 编程相关的问题?

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

计算字符串中的字符数

嗨,我的代码中有一个问题,我必须计算表达式中使用的变量,当两个或多个变量相同时,应将其计算为1。例如,a+ab=使用的变量总数:2。问题是当我输入a+a=使用的变量总数:2时。 这是我的代码:

public void simplify(String strexp){
    int ex =strexp.length();

    for (int a=0;a<=ex-1;a++){
        if(a==0)
        {
        if (Character.isLetter(strexp.charAt(a)))
        {
        b++;
       }


        }
        else{
        for(int c=0;c<=a-1;c++){
              if (Character.isLetter(strexp.charAt(c))==Character.isLetter(strexp.charAt(a)))
              {

                System.out.println("equal");
                break;
              }
              else if (Character.isLetter(strexp.charAt(c))!=Character.isLetter(strexp.charAt(a)))
              {
             //if(c==a-1)
              //{
               b++;
               System.out.println("nomatch");
           //  }
               }
        }
        }
        }
   JOptionPane.showMessageDialog(null, b);
    }

共 (2) 个答案

  1. # 1 楼答案

    使用列表来计算变量的总量

    public static int simplify(String strexp) {
        int length = strexp.length();
    
        List<Character> usedVariables = new ArrayList<Character>();
        for (int i = 0; i < length; i++) {
            char c = strexp.charAt(i);
            if (Character.isLetter(c) && !usedVariables.contains(c)) {
                usedVariables.add(c);
            }
        }
    
        return usedVariables.size();
    }
    
    public static void main(String[] args) {
        System.out.println(simplify("x + b = d"));
        System.out.println(simplify("x + x = a"));
        System.out.println(simplify("x + x = x / 2"));
    }
    

    这是打印出来的

    3
    2
    1
    
  2. # 2 楼答案

    你需要跟踪你看到的变量。一种方法可能是使用Set<char>。每当你看到一个角色,就把它添加到集合中。唯一运算符的数量将是集合中的字符数