java循环卡在无限循环中
为什么这段代码没有结束。我已经给出了所需的字符串输入和k输入,但我不知道为什么它没有结束。请提供一些见解
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;
while(first < last){
if(l.get(first) + l.get(first + 1) == k || l.get(first) == k){
count++;
}
}
if(count % 2 == 0){
System.out.println("B");
}
System.out.println("A");
}
}
# 1 楼答案
你的意见目前还可以。问题是
first
和last
在整个迭代过程中保持不变。在while循环中添加first++;
,以便在每次迭代中first
值递增