Reputation: 49
I have been working on a generating password method that will change every "S" to $.
Note I take the phrase in from another class and it will always be greater than 8 characters
String key;
String store;
key = phrase.substring(0,1).toUpperCase();
phrase = key + phrase.substring(1,phrase.length());
System.out.println(phrase);
System.out.println(phrase.length());
for(int i = phrase.length(); i>0; i--) {
int sKey = phrase.indexOf('S');
store = "$" + phrase.substring(sKey+1,phrase.length());
phrase =phrase.substring(0,sKey)+store;
System.out.print(phrase);
}
}
However I always get this error afterwards
Exception in thread "main" Te$taaaajava.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at edu.ilstu.Security.generatePassword(Security.java:15)
at edu.ilstu.SecurityApp.main(SecurityApp.java:57)
Upvotes: 1
Views: 3295
Reputation: 15144
You take phrase.indexOf('S')
on a string without checking the return value. If there is no match, the method returns -1
. You then use this index as the upper bound of a substring, which crashes the program.
You would want a different algorithm even if you got it correct, if I understand correctly what you want to do. There is no reason both to search the string for each occurrence of the character you want and also to write a loop decrementing the length by 1. Also, avoid copying long arrays and strings if possible.
Upvotes: 1
Reputation: 49
I am not sure if this is the correct way to do it. However, I have found adding an if statement actually fixed this code and stopped the for loop when the index becomes -1
String key;
String store;
key = phrase.substring(0,1).toUpperCase();
phrase = key + phrase.substring(1,phrase.length());
for(int i = phrase.length(); i>0; i--) {
int sKey = phrase.indexOf('S');
if(sKey >= 0) {
store = "$" + phrase.substring(sKey+1,phrase.length());
phrase =phrase.substring(0,sKey)+store;
}else {
i=0;
}
}```
Upvotes: 0
Reputation: 543
Index out of range exception value of -1 means the requested symbol, in this case, S, is not found.
Upvotes: 2