我正在尝试解决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(" ");
}
}
}
答案 0 :(得分:0)
我会说你在正确的轨道上,但有些地方需要仔细检查。第一个循环似乎有一些问题:j++
可能超出了数组的边界 - 至少如果你的字符串末尾有空格。而整个循环本身似乎忽略了该行的最后一个字符。
你确定你甚至需要这个第一个循环吗?如果我理解正确,Scanner
的{{1}}会在空格之间给你一些字符串;在连续两个空格的情况下,我认为它应该返回一个空字符串。在这种情况下,您可以像在函数末尾一样循环列表,并在列表中遇到空字符串时打印空格字符。否则只需向后打印单词,就像你已经做的那样(除了在最后一个循环中它应该是next()
而不是m--
)。
但是如果m++
在有两个或多个连续空格字符时不会给你空字符串,我打赌字符串的Scanner
方法应该有效。