You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java开发DFA课程项目时for循环内整数K始终为0无法正常计数如何修复

问题原因

你的代码核心错误是所有状态判断的if分支完全独立执行:当你在前面的分支修改了k的值后,后续的if分支会立刻用新的k值做判断,导致刚完成的状态跳转被后续分支的逻辑覆盖。

举个实际运行的例子就很清楚:
初始k=0(对应状态a),输入字符为'1'时:

  1. 第一个if匹配规则states[k] == 'a' 且输入为'1',k自增变为1
  2. 程序继续执行后续的状态b判断分支,此时k已经是1,刚好匹配states[k] == 'b' 且输入为'1'的规则,触发k = 0的逻辑
  3. 一轮循环结束后k变回0,看起来就像没有发生过跳转

修复方案

把所有状态判断的分支改成if-else if串联结构,保证单次字符处理流程中,只会匹配最开始的初始状态对应的分支,不会用修改后的k重复做状态匹配。
同时可以优化:提前把测试字符串转成字符数组存储,避免循环中反复调用toCharArray()生成重复对象。

修改后的示例代码如下:

public static void give(char[] states, String testString) {
    int k = 0;
    char[] inputChars = testString.toCharArray(); // 提前转成字符数组
    for (int i = 0; i < inputChars.length; i++) {
        System.out.println("i is: " + i);
        System.out.println("k is: " + k);
        System.out.println("State is: " + states[k] + "\n");
        char currentState = states[k]; // 提前存储当前状态,避免k修改后影响状态匹配逻辑
        char currentInput = inputChars[i];
        
        if (currentState == 'a' && currentInput == '0') {
            k = 0;
        } else if (currentState == 'a' && currentInput == '1') {
            k++;
        } else if (currentState == 'b' && currentInput == '0') {
            k++;
        } else if (currentState == 'b' && currentInput == '1') {
            k = 0;
        } else if (currentState == 'c' && currentInput == '0') {
            k++;
        } else if (currentState == 'c' && currentInput == '1') {
            k = 0;
        } else if (currentState == 'd' && currentInput == '0') {
            k = 0;
        } else if (currentState == 'd' && currentInput == '1') {
            k++;
        } else if (currentState == 'e' && currentInput == '0') {
            System.out.println(states[k]);
        } else if (currentState == 'e' && currentInput == '1') {
            System.out.println(states[k]);
        }
    }
}

内容的提问来源于stack exchange,提问作者Harl23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:54:04