This method is supposed to get the number of occurrences of a certain pattern and return the int value. I keep getting this error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Code
public int getCount(String pattern){
int occerenceOfPattern = 0;
for (int i = 0; i <= strand.length(); i++) {
if (strand.substring(i, i + pattern.length()) == pattern) {
occerenceOfPattern++;
}
}
return occerenceOfPattern;
}
i <= strand.length()
.length() returns the total length of the string and the indexes of the string start at 0. So if i is equal to the string length you will get an out of bounds. To fix this use:
i <= strand.length() - 1
or
i < strand.length()
You're iterating too far on your String.
For substring, charAt, or any method that requires to you to use an exact numerical value to get at a character or a group of characters, the size of the String is defined as the result of the length() call minus 1.
It's like an array (since it is backed by a char[]): "cat" has length 3, but it's zero based, so I can only go up to 2.
Change your condition to be strictly less-than, and not less-than or equal to.
StringIndexOutOfBoundsException comes when the index where you are pointing to is null(does not exist). Here the problem I see is in strand.length().
for (int i = 0; i < strand.length(); i++)
This should work fine
public int getCount(String pattern){
int occerenceOfPattern = 0;
for (int i = 0; i < strand.length(); i++) {
if (strand.substring(i, i + pattern.length()) .equals(pattern)) {
occerenceOfPattern++;
}
}
return occerenceOfPattern;
}
(changed == to .equals. for reason see this post) Use equalIgnoreCase if it is case insensitive.
length() is already described in rest of the answers
== tests for reference equality.
.equals() tests for value equality.
How to compare Strings in java
You need to correct your condition check in loop and also add new check inside loop block:
public int getCount(String pattern){
int occerenceOfPattern = 0;
for (int i = 0; i < strand.length(); i++) { // Updated check
if((i + pattern.length()) >= strand.length()) // New condition to avoid exception
break;
if (strand.substring(i, i + pattern.length()) == pattern) {
occerenceOfPattern++;
}
}
return occerenceOfPattern;
}
New added check can also be handled in loop condition itself.
i <= strand.length() in your for loop is your problem...
length() returns the number of elements in an Array. Always remember that index starts from 0. So, if length is 5, you have 5 elements 0,1,2,3 and 4. So, you have to use i<strand.length();
You get StringIndexOutOfBoundsException because element with index "length-1" is the last element and you are trying to access element with index="length".
3 problems...
Change <= to < in your loop.
You also need to limit the right side of the substring to not be past the end of the string.
And you need to use .equals() not ==.
public int getCount(String pattern){
int occerenceOfPattern = 0;
for (int i = 0; i < strand.length(); i++) {
if (strand.substring(i, Math.min(i + pattern.length(), strand.length())).equals(pattern)) {
occerenceOfPattern++;
}
}
return occerenceOfPattern;
}
Related
This program is intended to match a string to another string and calculate the number common substrings they share. For some reason, it always prints the same incorrect values. Using the same methods, how can I make this code work as I intended it to?
public static void main(String[] args) {
String secret = "word";
String guess = "gzek";
int count = 0;
int length = secret.length();
int guess_length = guess.length();
for(int i=0;i<length-1;i++){
if(secret.substring(i, i).equals(guess.substring(i, i))){
count ++;
}
}
System.out.println(count);
}
According to its JavaDoc, the end index parameter of the substring() method is exclusive:
#param beginIndex the beginning index, inclusive.
#param endIndex the ending index, exclusive.
This means that secret.substring(i, i) returns the sub-string from i to i-1, which is always the empty string "". Therefore, secret.substring(i, i).equals(guess.substring(i, i)) always compares "" with "" and is always true. Your code effectively counts the number of characters in guess.
If you want to compute all sub-strings of a string s, you need two loops, one for the start index and one for the end index:
for (int i = 0; i < s.length(); i++) {
for (int j = i; j < s.length(); j++) {
String substring = s.substring(i, j + 1);
// further code ...
}
}
Note that this only computes the sub-strings of one string. If I understood your question correctly, you want to compute all common sub-strings of two strings. To do this, you will need a total of four nested loops. This is going to be very slow even for small strings. There are of course much faster approaches, but they are also more complex.
Ok so I currently have a String array which contains keycodes, and i want to check if the first element shares common specifications with the second , e.g. [012] has similar elements with [123]. I currently loop through the length of the first element, and then loop through the length of the second element, and compare those two like this:
If(A[1].charAt(j) == A[2].charAt[i]) c++; c is a counter to show how many
common elements the keycodes have. Here is the method i created
static boolean hasSimilarity(String[] A, int K, int i){
int c = 0;
for(int j = 0;j<K;j++){
for(int m = j;m<K;m++){
if(A[i].charAt(j) == A[i+1].charAt(m)) c++;
}
}
return c != 0;
}
And here is the execution of it in the Main class:
int max = -1;
findSimilar FS = new findSimilar();
for (int i = 0; i < sum.length -1; i++) {
boolean hasSimilar = FS.hasSimilarity(key,K,i);
if (!hasSimilar) {
int summ = sum[i] + sum[i + 1];
System.out.println(summ);
if (summ > max) {
max = summ;
}
}
}
When i run this, i get a java.lang.StringIndexOutOfBoundsException out of range: 0 . What am I doing wrong? Is there any better way to compare two keycodes in order to find similarities beetween them?
This error:
java.lang.StringIndexOutOfBoundsException out of range: 0
Can only occur if one of your strings is the blank string "".
You are attempting to get charAt(0) when there is no char 0 (ie first char).
——-
You would avoid this problem, and have a far more efficient algorithm, if you first collected the counts of each character then compared those, which would have time complexity O(n), whereas your algorithm is O(n2) (albeit that it seems your n - the length of your inputs - is small).
I am trying to display the last index of an item in array, an example:
{6,4,7,3,11,4} Last index of 4 = 5
I have written this method so far:
public int lastIndexOf(int[] nums, int num) {
int found = 0;
for (int i = nums.length; i < 0 ; i--) {
if (nums[i] == num) {
return i;
}
}
return -1;
}
Why does this not work? I am under the impression that you need to start the for loop at the start of the arrays length and then work backwards. I want to be able to use a for loop to do this, I set up a condition if there are no occurrences of the number to return -1 but when I am running this code I always return -1 no matter what numbers I am putting in.
How would I solve this using a for loop?
Your for loop conditions are not correct. Should be
for (int i = nums.length-1; i >= 0 ; i--) {
The "i<0" from before prevented it from entering the loop.
But the "i = nums.length" would have given you an Index out of bounds error. Need to subtract by 1 because Arrays are 0 indexed
You can also turn the array into list and use List's lastIndexOf method so you don't have to implement yourself.
Arrays.asList(nums).lastIndexOf(num)
note that lastIndexOf return -1 if num is not found in nums
class Solution {
public String longestCommonPrefix(String[] strs) {
String result = new String("");
char compareElement;
int i;//index of strs
int j;//index of the first one of string
for(j = 0; j < strs[0].length(); j++){
compareElement = strs[0].charAt(j);
for(i = 1; i < strs.length; i++){
if(compareElement == strs[i].charAt(j)){
if(i == strs.length - 1)
result += compareElement;
else
continue;
}
else{
break;
}
}
}
return result;
}
}
Test sample is
Input: ["flower","flow","flight"]
Output: "fl"
hi there I have got a problem with string in Java in my 4th small program in Leetcode. The aim of this function is to find the longest common prefix string amongst an array of strings. But the exception
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of
range: 4
at java.lang.String.charAt(String.java:614)
at Solution.longestCommonPrefix(Solution.java:11)
at __DriverSolution__.__helper__(__Driver__.java:4)
appears over again.
Has someone any idea? Thanks!
I think this is where you go wrong:
if(compareElement == strs[i].charAt(j))
j can become too large as it goes from 0 to strs[0].lenght() (see your outer loop).
If strs[i].lengt() is smaller than strs[0].length() you get an StringIndexOutOfBoundsException.
When you iterate through the comparison strings, you're never checking the length of the string you're comparing. In your example the test case flow. The char at index 4 doesn't exist since only indices 0-3 are defined. if(compareElement == strs[i].charAt(j)){ when j is 4 it'll mess up. In order to fix it you have to make sure you're not going past the length of the string. In addition to that look up what a StringBuilder is, for this small of a test case it won't matter however as you go up larger it will.
Your code fails if you have an element in the array which is shorter than the first element. You need to check that j is still smaller than the length of the string you're comparing:
public String longestCommonPrefix(String[] strs) {
String result = new String("");
char compareElement;
int i;// index of strs
int j;// index of the first one of string
for (j = 0; j < strs[0].length(); j++) {
compareElement = strs[0].charAt(j);
for (i = 1; i < strs.length; i++) {
if (j < strs[i].length() && compareElement == strs[i].charAt(j)) {
if (i == strs.length - 1)
result += compareElement;
else
continue;
} else {
break;
}
}
}
return result;
}
I am trying to split strings in substrings of two chararters for example for the input: "ABCDE" i want to get the substrings "AB" "BC" "CD" "DE".
I tried with this:
String route = "ABCDE";
int i = 0;
while(i < route.length()) {
String sub = route.substring(i,i+2);
System.out.println(sub);
i++;
}
but the index (i) gets out of range int the last iteration and causes an error.
is there any way to do this without getting the index (i) out of range ?
You need to change the loop condition.
while(i < route.length()-1)
In your code i goes till (length-1) and than in the substring(i,i+2) function you gives end index i+2. It is higher than largest index of string.
Also, As far as I know calling a library function in a loop condition is not considered a good practice.
In each iteration you call this function which is time consuming.
control goes to that subroutine in each iteration.
A good alternative to this would be to store the length in a variable and use that in a condition.
int temp = route.length()-1;
while(i<temp){
This should work fine
String route = "ABCDE";
if( route.length() > 2){
int i = 0;
do {
String res = route.substring(i,i+2);
System.out.println(res);
i++;
} while (i + 1 < route.length());
}
else{
System.out.println(route);
}
Edit: Added boundary case for the string has length less than 2
Add check for the size of the string to trap the error:
String route = "ABCDE";
int i = 0;
while(i < route.length()) {
if(i < route.length() - 1) {
String sub = route.substring(i,i+2);
System.out.println(sub);
} else {
String sub = route.substring(i,i+1);
System.out.println(sub);
i++;
}
So whenever the i counter almost close to string size, get the last char.
You are getting an StringIndexOutOfBoundsException because you are trying to access an index of the String that doesn't exist.
To fix this, change your loop condition from
while(i < route.length())
to
while(i < route.length() - 1)
Without the -1 on the last iteration of the while loop i + 2 is equal to 71 which is out of the Strings bounds.
Another (cleaner) solution to this problem is a for loop:
for(int i = 0; i < route.length() - 1; i++) {
System.out.println(route.substring(j, j + 2));
}
The for loop in this situation is just shorter as the declaration, conditional, and increment statements are all in one line.
1: This 7 reduces to 6 since the endIndex of substring is exclusive.
As denis already pointed out, the bug in the code is in the loop condition.
Should be: while(i < route.length() - 1)
. However, how about simplifying this logic to use a for loop.
String route = "ABCDE";
for (int i=0; i+2<=route.length(); i++)
System.out.println(route.substring(i,i+2));
you can not use
i < route.length(),because when i = 5, String sub = route.substring(i,i+2); the i+2=7,is out of index,so use i<route.length instead