【问题标题】:Integer variable does not update when if condition is true如果条件为真,整数变量不会更新
【发布时间】:2019-12-13 16:56:39
【问题描述】:
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;
    }
}

程序检查从命令行输入的两个字符串中的不同字母。每当有匹配项时,变量“stored”应该更改为 1,以避免对变量“ctr”进行额外扣除。但是,由于某种原因,不仅“存储的”值不会改变,数组“数组”也不会在匹配时更新其元素。我不知道如何修复它——看起来没有什么不正确的。

【问题讨论】:

  • 欢迎来到 Stack Overflow。不幸的是,很难准确地理解您的代码要做什么,或者哪里出错了。你的输入是什么?你究竟在哪里期望发生一些没有发生的事情?你调试过代码吗?
  • 您尝试过使用分步调试器吗? stackoverflow.com/questions/18977397/…

标签: java


【解决方案1】:

这是你写的:

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) {
        ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-10
    • 2015-03-07
    • 1970-01-01
    • 2014-06-17
    • 2014-11-28
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    相关资源
    最近更新 更多