Java代码输入参数后无法终止陷入无限循环,请求问题排查指导
问题分析
- 死循环直接原因:
while(first < last)循环体内未修改first或last的取值,初始first=0,只要字符串长度≥2,first < last的判断永远为真,程序会一直卡在循环中无法向下执行。 - 字符运算不符合预期:代码直接对
Character类型做加法、相等判断,实际比较的是字符的ASCII编码值,而非字符代表的数字值。例如字符'0'的ASCII值为48,若你的需求是判断字符对应的数字大小,需要先做转换:l.get(first) - '0'。 - 存在数组越界风险:循环中直接访问
l.get(first + 1),如果first等于数组最大下标时,first + 1会超出列表下标范围,触发下标越界异常。 - 输出逻辑错误:当前代码无论
count是否为偶数,最终都会执行System.out.println("A");,若你的需求是根据count奇偶性二选一输出,需要把第二个输出放到else分支中。
修复参考
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int k = sc.nextInt(); ArrayList<Character> l = new ArrayList<>(); for(int i=0; i<s.length(); i++){ l.add(s.charAt(i)); } int count = 0; int first = 0; int last = s.length() - 1; // 循环内更新first变量,避免死循环 while(first < last){ // 转成数字值再做判断 int cur = l.get(first) - '0'; int next = l.get(first + 1) - '0'; if(cur + next == k || cur == k){ count++; } first++; } if(count % 2 == 0){ System.out.println("B"); }else{ // 加else分支实现二选一输出 System.out.println("A"); } } }
注:以上修复仅解决现有代码的明显错误,你可根据实际业务需求调整判断逻辑与循环规则。
内容的提问来源于stack exchange,提问作者sailesh kumar
相关产品推荐
相关产品推荐

