【发布时间】:2012-02-13 11:40:52
【问题描述】:
您好,我的代码有问题,我必须计算表达式中使用的变量,当两个或多个变量相同时,应计为 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);
}
【问题讨论】:
-
您可以使用正则表达式来查找所有变量,然后通过一些数组唯一函数或其他方法。
-
ab和AB是否相等? -
你要数哪一个:变量数还是字符数?我可以用一个或多个字符命名一个变量;例如:a、变量、ab、a1
-
因为您的示例包括
a + ab,它的变量总数为二(2)。所以,我假设每个变量的长度可以超过一个字符。 -
对不起,你的标题误导了;它与您想要实现的目标不同......
标签: java string for-loop count