这个类是测试我的2种方法(“取景器”)是否工作(不幸的是他们不是)。 endfinder()意味着返回提供的字符串中下一个非空格字符的索引; endfinder2()是为了返回从endfinder找到的索引开始的单词的终点。它们旨在用于从字符串中拉出多个单词并用空格分隔的单词。我已经浏览了几个小时,肯定有一些明显的答案,但我觉得我正在慢慢发疯。请帮我理解为什么我的代码不起作用
我已经删除了所有的输出,我用它来测试代码在很多尝试找出什么是错的,使它更清洁。
基本上,我发现endfinder()总是返回0,出于某种原因,endfinder2()会一直运行,直到达到中断为止(我认为这会发生,因为它在我添加之前会无限循环) 。
我想要的结果是开始= 3,结束= 6这将使其输出“[一]”。
结果我得到:
[一二三]启动= 0,结束= 17
这里是我的代码:
import java.io.*;
import java.util.*;
public class test {
static String answer, container;
static int start = 0, end = 1;
public static int endfinder(String perspective) {
int holder = start;
while (perspective.substring(holder, (holder + 1)) == " ") {
holder++;
if (holder == perspective.length())
break;
}
return holder;
}
public static int endfinder2(String perspective) {
int holder = end;
while (perspective.substring(holder, (holder + 1)) != " ") {
holder++;
if (holder == perspective.length())
break;
}
return holder;
}
public static void main(String Args[]) {
System.out.println();
System.out.println();
container = " one two three";
start = endfinder(container);
end = start + 1;
end = endfinder2(container);
System.out.println("[" + container.substring(start, end) + "]");
System.out.println();
System.out.println("start: [" + start + "] end: [" + end + "]");
System.out.println();
}
}
顺便说一句,两个提示。首先,你应该命名你的类为'Test'(而不是'test'),你应该尽量避免在'static'上下文中工作。为什么没有'main'方法的第一行:'Test test = new Test();'。 – vikingsteve 2014-10-29 13:51:43
@看看我的答案,这是你想要的。 – brso05 2014-10-29 13:57:45