gpt4 book ai didi

java - Java 计算字符串中的字符数

转载 作者:行者123 更新时间:2023-12-01 05:29:20 25 4
gpt4 key购买 nike

您好,我的代码中有一个问题,我必须计算表达式中使用的变量,当两个或多个变量相同时,它应该计为 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);
}

最佳答案

使用列表统计变量总数

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

关于java - Java 计算字符串中的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9259858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com