I have a while loop that is supposed to seperate a word into individual letters... It works but then when ever i try to check if a substring that does not exist is null it throws exceptions...
private static void seperateWord(String word) {
boolean running = true;
int count = 0;
while (running) {
if (word.substring(count, count + 1).equals("null")) {
running = false;
return;
} else {
letter[count] = word.substring(count, count + 1);
System.out.println(letter[count]);
count++;
}
}
}
It does output all the letters correctly until it gets to the end of the string and has nothing left to read... as in it just does not exist. It throws this exception...
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.substring(Unknown Source)
at Class.seperateWord(Class.java:33)
at Class.main(Class.java:13)
Line 33 is :: if (input.substring(count, count + 1).equals("null")) {
Line 13 is just where I call the method.
The text I entered is "abc"
Thanks in advance for any help!
You're trying to get the substring going from index 3 to index 4 on a string which has only 3 characters. This is why you get an exception.
Moreover, input.substring(count, count + 1).equals("null") will obviously never be true. How could a string of 1 character ever be equal to the string "null", which has 4 characters?
Read the API doc of the String class. It has a length() method which returns the length of the string, and that you should use to stop your loop. It also has a charAt() method which returns the character at a given index.
Related
What does that mean? The length of the string is too long or there is error in my code?
public class Program {
public static String flipEndChars(String s) {
if(s.charAt(0) == s.charAt(s.length())){
return "Two's a pair.";
}
else if(s.length()<3){
return "incompatible";
}
else
return s.charAt(s.length()) + s.substring(1,s.length()) + s.charAt(0);
}
}
the issue is with this part :
s.charAt(s.length())
It's trying to access a character beyond the length of your string. The indexation is zero based, so the last character of a string is always at index s.length() - 1
String.charAt(int) returns the char at the specified index, where 0 is the first character, 1 is the second character, 2 is the third, and so on.
"hello".charAt(0) returns the character h.
String.length() returns the length of the string.
"hello".length() returns 5. So if you call "hello.charAt(5)", this will get the 6th character in the String "hello", which does not exist. This will throw an IndexOutOfBoundsException.
I hope this helps.
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)
Index out of range exception value of -1 means the requested symbol, in this case, S, is not found.
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.
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;
}
}```
Disclaimer: This is a bit of a homework question. I'm attempting to write a contains(java.lang.String subString) method , that returns an int value representing the index of the comparison string within the primary string, for a custom-made String class.
Some of the rules:
No collection classes
Only charAt() and toCharArray() are allowed from the java String class (but methods from other classes are allowed)
Assume length() returns the length of the primary string (which is exactly what it does)
My Code:
public int contains(java.lang.String subString) {
this.subString = subString;
char[] arrSubStr = this.subString.toCharArray();
//Create initial fail
int index = -1;
//Make sure comparison subString is the same length or shorter than the primary string
if(arrSubStr.length > length()) {
return index;
}
//Steps to perform if initial conditions are met
else {
//Compare first character of subString to each character in primary string
for(int i = 0; i < length(); i++) {
//When a match is found...
if(arrSubStr[0] == this.content[i]) {
//...make sure that the subString is not longer than the remaining length of the primary string
if(arrSubStr.length > length() - i) {
return index;
}
//Proceed matching remainder of subString
else {
//Record the index of the beginning of the subString contained in primary string
index = i;
//Starting with second character of subString...
for(int j = 1; j < arrSubStr.length;) {
//...compare with subsequent chars of primary string,
//and if a failure of match is found, reset index to failure (-1)
if(arrSubStr[j] != this.content[j+i]) {
index = -1;
return index;
}
//If we get here, it means whole subString match found
//Return the index (=i) we set earlier
else {
return index;
}
}
}
}
}
}
return index;
}
Results from testing:
Primary string: asdfg
Comparison string: donkey
Result: -1 [PASS]
Primary string: asdfg
Comparison string: asdfg
Result: 0 [PASS]
Primary string: asdfg
Comparison string: g
Result: 4 [PASS]
Primary string: asasasf
Comparison string: asd
Result: 0 [FAIL] (should be -1)
Primary string: asasasf
Comparison string: asf
Result: 0 [FAIL] (should be 4)
The comments reflect how the code is intended to work. However its clear that when it reaches the second for loop, the logic is breaking down somehow to give the results above. But I can't see the problem. Could I get a second set of eyes on this?
//If we get here, it means whole subString match found
//Return the index (=i) we set earlier
else {
return index;
}
This assumption is not correct unfortunately. If you get there, it means that the second character of both substrings are identical since the if-else statement will only get executed once and both ends contains a return.
The way to solve this is probably easy now that I've diagnosed the problem but I want to go a bit further with this. The way we try to write code on a daily basis is a way in which the code we use can be maintainable, reusable and testable.
This means basically that the function we have here could be easily sliced up in different little functions invoked one after the other for which we could write unit tests and receive a quick feedback on whether a set of logical statements fit or not.
With suggestions from Jai and azurefrog in the comments, I was able to solve the issues by re-writing the logic to the following (somewhat abridged):
if(arrSubStr.length > length()) {
return index;
}
//Steps to perform if initial conditions are met
else {
//Compare first character of subString to each character in primary string
for(int i = 0; i < length(); i++) {
//When a match is found...
if(arrSubStr[0] == this.content[i]) {
//...make sure that the subString is not longer than the remaining length of the primary string
if(arrSubStr.length <= length() - i) {
//Record the index of the beginning of the subString contained in primary string
index = i;
//Starting with second character of subString...
for(int j = 1; j < arrSubStr.length; j++) {
//...compare with subsequent chars of primary string,
//and if a failure of match is found, reset index to failure (-1)
if(arrSubStr[j] != this.content[j+i]) {
index = -1;
break;
}
}
}
}
}
}
return index;
Essentially, I removed all of the return statements from within the loops. Simply setting the index value appropriately and making use of the final (outside) return statement was, in hindsight, the correct way to approach the problem. I then also added a break; to the inner for loop to make sure that a failure to match would continue the loop ticking through. I'm sure there's still unnecessary code in there, but while its still passing the requisite tests, I'm encouraged to leave it the hell alone. :)
I'm still a novice at Java, so I hope this explanation made sense.
I tried to get string from long string which is Firebase URL
"https://firebasestorage.googleapis.com/v0/b/No-manworld-3577.appspot.com/o/Contacts%2F1510361061636_Julien_Vcf?alt=media&token=c0bff20d-d115-4fef-b58c-4c7ffaef4296"
Now if you notice there is under score before and after name Julien in above string. I am trying to get that name but i am getting
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Here is my piece of code
String s="https://firebasestorage.googleapis.com/v0/b/No-manworld-3577.appspot.com/o/Contacts%2F1510361061636_Julien_Vcf?alt=media&token=c0bff20d-d115-4fef-b58c-4c7ffaef4296";
String newName=s.substring(s.indexOf("_")+1, s.indexOf("_"));
System.out.println(newName);
As said in my comment, when using substring, the first number has to be smaller than the second one.
In your case, you are calling substring with x + 1 and x. x + 1 > x thus substring fails, with x being s.indexOf("_").
I understand that you are trying to get the second indexOf of _.
Here is code that would in your case yield Julien:
String s = "...";
int start = s.indexOf("_") + 1;
int end = s.indexOf("_", start);
// name will hold the content of s between the first two `_`s, assuming they exist.
String name = s.substring(start, end);
If requirements are not clear on which 2 _ to select then here is Java 8 Stream way of doing it ..
public class Check {
public static void main(String[] args) {
String s = "https://firebasestorage.googleapis.com/v0/b/No-manworld-3577.appspot.com/o/Contacts%2F1510361061636_Julien_Vcf?alt=media&token=c0bff20d-d115-4fef-b58c-4c7ffaef4296";
long count = s.chars().filter(ch -> ch == '_').count();
if (count == 2) {
System.out.println(s.substring(s.indexOf('_') + 1, s.lastIndexOf('_')));
} else {
System.out.println("More than 2 underscores");
}
}
}
Why your code didn't work?
Let assume s.indexOf("_") gets some positive number say 10 then below translates to ...
String newName=s.substring(s.indexOf("_")+1, s.indexOf("_"));
String newName=s.substring(11, 10);
This will give StringIndexOutOfBoundsException as endIndex < beginIndex for subString method.
hey guys i'm a newby to programming in java and i'm trying to figure out why i'm getting a string out of bounds on my secondary loop. I'm trying to create a spell checker & i'm not sure maybe i'm not doing this exactly right. I'm trying to check the word of a sentence and compare it to the other array of words and char each character until end of the length of toCheck, but doesn't work :\
Any help would be greatly appreciated!! thank you in advance
public static String suggestions (String toCheck, String [] words, Scanner kb)
{//start
int length=toCheck.length(),total=0, count = 0;
for(int x = 0;x<words.length;x++)
{
if(words[x].charAt(0)==(toCheck.charAt(0)))
for(int j = 0;j<length-1;j++)
{
if(toCheck.charAt(j)==words[x].charAt(j))
count++;
}
if(count>=((words[x].length())/2))
total++;}
System.out.println(total);
//System.out.printf("Not found - %s",toCheck);
//System.out.println("\nChoices 1 leave as it 2. Type replacement 3 Pick one " + Arrays.toString(suggest));
return toCheck;
}//end of suggestions
error message shown
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:686)
at CSCD210HW4.suggestions(CSCD210HW4.java:59)
at CSCD210HW4.main(CSCD210HW4.java:44)
Why don't you use compareTo instead of manual checking for different character. It will be more easy.
For example
count = Math.abs(words[x].compareTo(toCheck));
//It will return the difference of character in both string.
// Suppose words[x] = "abc" and toCheck = "adc" then count will be 1.
length is the size of the word to check.
you're trying to access words[x].charAt(j) which does not have to exist.
j is the length of the string toCheck
You can use the below code:
public class check {
public static boolean suggestions (String toCheck, ArrayList<String> words)
{
for(String word: words )
{
return (toCheck.toLowerCase().equalsIgnoreCase(word));
}
return false;
}
}