public class test
{
static Scanner store = new Scanner(System.in);
public static void main(String[] args)
{
String str1 = args[0];
String str2 = args[1];
System.out.printf("%nThere are %d dissimilar characters in the two strings.%n", CountNotSim(str1, str2));
}
public static int CountNotSim(String str1, String str2)
{
String s1 = str1.toLowerCase();
String s2 = str2.toLowerCase();
char[] a1 = new char[s1.length()];
char[] a2 = new char[s2.length()];
for (int g = 0; g < s1.length(); g++)
a1[g] = s1.charAt(g);
for (int h = 0; h < s2.length(); h++)
a2[h] = s2.charAt(h);
int check = 0, stored;
char[] array = new char[26];
int ctr = s1.length() + s2.length();
for (int i = 0; i < a1.length; i++)
{
check = 0;
stored = 0;
for (int j = 0; j < a2.length; j++)
{
if (a1[i] == a2[j])
{
check++;
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ')
if (stored == 0)
array[k] = a1[i];
if (a1[i] == array[k])
{
stored = 1;
break;
}
}
System.out.print(stored + "/ ");
}
}
if (check > 0)
{
if (stored == 0)
ctr -= (check + 1);
else if (stored == 1)
ctr--;
}
System.out.print(ctr + " "); //checker
}
System.out.println();
return ctr;
}
}
程序检查从命令行输入的两个字符串中是否存在不同的字母。只要存在匹配项,变量“存储”应该更改为1,以避免对变量“ ctr”进行额外扣除。但是,由于某种原因,不仅存在“ stored's”值不变,而且只要存在匹配项,数组“ array”也不会更新其元素。我对如何解决它一无所知-看起来没有什么不对。
答案 0 :(得分:0)
您是这样写的:
char[] array = new char[26];
...
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ') {
...
但是您只需设置array
的长度而不是其内容。
作为char
数组,它填充有默认的char值,该值不是字符空间而是值
0
(不是 0,但数值为0)
所以array[k] == ' '
永远不会是真的。
尝试一下:
for (int k = 0; k < 26; k++)
{
if (array[k] == 0) {
...