Reputation: 85
I'm trying to reverse a sentence. (if the sentence is "i am a cat", then the result should be "cat a am I") The problem is that I'm getting an index out of bounds error, I'm not sure how to fix the problem. Not sure if my index is wrong or if the substring part is wrong. I'm just a beginner in Java, so any help is really appreciated. error: String index out of range: -1
Thanks
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();
}
}
}
Upvotes: 0
Views: 419
Reputation: 77454
From the Java documentation of String
:
public int indexOf(int ch)
...
If no such character occurs in this string, then -1 is returned.
are you prepared for that there is no more whitespace?
For example at the last iteration...
But it looks like there are other bugs, too.
Upvotes: 1
Reputation: 31184
Your problem would be with a line like the following:
int ws = line.indexOf(" ");
String word = line.substring(0,ws);
whenever indexOf
doesn't find what it's looking for, it will return -1. If you ever try to use that index on the string, you'll be indexing at -1
which is out of bounds.
it looks like you're trying to find the space in a line that has no space.
Upvotes: 0