這個類是測試我的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