我試圖解決this problem,但我不知道爲什麼我的解決方案無法正常工作。我的調試嘗試告訴我,該解決方案試圖訪問某些數據結構邊界之外的索引,但這對我來說沒有意義,因爲它似乎像我的for-loop測試那樣。反轉打印單詞,同時保持空格的順序和數量?
除此之外,此解決方案可能還有許多其他問題。
我也90%確定有一個更有效的方法來做到這一點。你能幫我弄清楚我在這裏做錯了什麼嗎?
如果有更有效的解決方案,它會是什麼?我正在努力處理以有效的方式跟蹤相同順序的相同數量的空格。
如果需要更多信息,請讓我知道,我會更新。
public static void printReversed(String line){
Scanner console = new Scanner(line);
ArrayList<String> list = new ArrayList<String>(); // keeps track of words in line
int spaceOccur = 0; // keeps track of the number of times there are spaces
while (console.hasNext()){
list.add(console.next());
spaceOccur++;
}
int[] spaces = new int[spaceOccur]; // keeps track of number of spaces for each occurrence of spaces
int count = 0; // for spaces[] traversal
// searches through original input to get number of spaces
for (int i = 0; i < line.length() - 1; i++){
if (line.charAt(i) == ' '){
int j = i;
int num = 0;
// traversal through spaces to count how many
while (line.charAt(j) == (' ')){ // first error here
num++;
j++;
}
i = j; // updates for loop counter to point past spaces
spaces[count] = num; // saves number of spaces
count++;
}
}
// printing reversed input
for (int k = 0; k < list.size(); k++){
// prints reversed chars
for (int m = list.get(k).length(); m > 0; m++){
System.out.print(list.get(k).charAt(m));
}
// prints spaces
for (int n = 0; n < spaces[k]; n++){
System.out.print(" ");
}
}
}