【发布时间】:2016-10-12 19:23:51
【问题描述】:
不知道为什么我的代码不起作用。它不断返回值 1 而不是我期望的值。
public class Lab5Example
{
public static void main(String[] args)
{
System.out.println(longestRun("aabbbccd"));
System.out.println("Expected 3");
System.out.println(longestRun("aaa"));
System.out.println("Expected 3");
System.out.println(longestRun("aabbbb"));
System.out.println("Expected 4");
}
public static int longestRun(String s)
{
int count = 1;
int max = 1;
for (int i = 0; i < s.length() - 1; i += 1) {
char c = s.charAt(i);
char current = s.charAt(i + 1);
if (c == current) {
count += 1;
}
else {
if (count > max) {
count = max;
}
current = c;
}
}
return max;
}
}
调试器工作不正常,所以我不知道什么不工作。
【问题讨论】:
-
为什么你认为调试器不工作?
-
你将
max初始化为1,永远不要修改,然后返回;除了1,它不能返回任何东西。 -
看起来像是没有正确设置
max的组合(根本),而且count需要在某个时候重置,否则您将连续计算所有重复字符而不是计数连续给定字符的最长序列。 -
@ScottHunter 我打了一些东西(一个选项或其他什么)并检查了一切,但无论如何,一旦我点击调试(对于我编写的任何代码),它不允许我完成这些步骤。 @resueman 是的,我发现了,将
count = max转为max = count
标签: java loops iteration counter