我试图颠倒一个句子。(如果句子是“我是一只猫”,那么结果应该是“我是猫”)问题是我得到一个索引越界错误,我不知道如何解决这个问题。不确定我的索引是否错误或子字符串部分是否错误。我只是Java的初学者,所以非常感谢任何帮助。错误:字符串索引超出范围:-1
谢谢
public class ReverseWords {
public static void main(String [] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter File Name: ");
String fileName = in.nextLine();
File f = new File(fileName);
try {
Scanner input = new Scanner(f);
int x = 1;
int n = input.nextInt();
while (x<n) {
String line = input.nextLine();
Queue<String> q = new LinkedList<String>();
q.add(line);
int ws = line.indexOf(" ");
String word = line.substring(0,ws);
ArrayList<String> a = new ArrayList<String>();
while (line.length() > 0) {
a.add(word);
q.remove(word);
}
System.out.println("Case #" + x);
for (int i = a.size(); i != 0; i--) {
System.out.print(a.get(i));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}