I am receiving the following error: java.lang.StringIndexOutOfBoundsException and I can't figure out why. Hopefully one of you knows a solution.
Thanks in advance.
static boolean palindromeCheck(String toBeChecked) {
String reverse = "", inputWithoutSpaces = "";
for (int i = 0; i < toBeChecked.length(); i++)
inputWithoutSpaces += toBeChecked.charAt(i);
for (int i = inputWithoutSpaces.length(); i > 0; i--) {
if (inputWithoutSpaces.charAt(i) != ' ')
reverse += inputWithoutSpaces.charAt(i);
}
return (inputWithoutSpaces == reverse) ? true : false;
}
charAt() accepts indices from 0 to length()-1, not from 1 to length().
The problem is here: for (int i = inputWithoutSpaces.length(); i > 0; i--)
Lets say the inputWithoutSpaces has length 10. i.e. indices 0 to 9. In your loop you start counting from the index inputWithoutSpaces.length() which is 10. Which does not exist. Hense the out of bounds exception.
Change it to for (int i = inputWithoutSpaces.length() - 1; i >= 0; i--) so you count from 9 to 0.
Your string has a specific length (lets say length: 5), but when you want to reverse iterate it you need to start from 4 and got down to 0. This means that you need to change your for loop and make it like this:
for (int i = inputWithoutSpaces.length() - 1; i >= 0; i--)
Related
What is the difference between using .length() and .length()-1 to find how many times letters occur in a string?
example:
for (int i = 0; i < str.length(); i++)
{
if (str.substring(i, i + 1).equals("e"))
{
count++;
}
}
System.out.println(count);
vs
for (int i = 0; i < str.length() - 1; i++)
{
if (str.substring(i, i + 2).equals("th"))
{
count++;
}
}
System.out.println(count);
Why can't we just use str.length() for both?
Because in the second example, you take a substring of 2 characters instead of one, like in the first example. Thus, by having the for loop only run until length - 1, the last iteration in the loop takes the characters at index length - 1 and length from the string. If you would check against length in the for loop, the substring in the last iteration would take the characters at position length and length + 1, which obviously wouldn't work.
You can make a function that works for all substrings. It would look like:
int countSubstrings(String str, String s) {
int count = 0;
for (int i = 0; i < str.length() - s.length() + 1; i++)
{
if (str.substring(i, i + s.length()).equals(s))
{
count++;
}
}
return count;
}
You need to stop looping over the string earlier as the substring that you are checking becomes longer.
(Note: the above method can be implemented more efficiently - using String.regionMatches - but it's for illustrating you question)
Unfortunately, in this case:
count = 0;
for ( int i = 0; i < str.length(); i++) {
if (str.substring(i, i + 2).equals("th")) {
count++;
}
}
System.out.println(count);
You will get the following exception.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 4, e
nd 6, length 5
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3756)
at java.base/java.lang.String.substring(String.java:1902)
at stackOverflow.Pattern.main(Pattern.java:22)
Because i+2 would check for the i+1 location of the string and that is beyond it's length.
If you were to use str.length() for the second one when it reaches the highest i value when it does a substring i+2 will go off the end of str
This is a simple code for Insertion Sort in Java. I tried reducing the lines of my Java code. But it cannot be done with this issue. I want to know why it cannot be done.
Code that I have tried (error happens in line number 9)
import java.util.Scanner;
public class InsertionSortModified {
public static int[] insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int pos = i;
while (pos > 0 && arr[pos-1] > temp)
arr[pos--] = arr[pos-1];
arr[pos] = temp;
}
return arr;
}
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int elementarr[] = new int[5];
for (int j = 0; j < 5; j++)
elementarr[j] = scnr.nextInt();
elementarr = insertionSort(elementarr);
for (int j = 0; j < elementarr.length; j++)
System.out.print(elementarr[j] + " ");
}
}
Error showing in the command window
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at InsertionSortModified.insertionSort(InsertionSortModified.java:9)
at InsertionSortModified.main(InsertionSortModified.java:22)
Program is working when the code modified to like this. (Line number 8 to 11)
while (pos > 0 && arr[pos-1] > temp) {
arr[pos] = arr[pos-1];
pos--;
}
Why I cannot use
arr[pos--] = arr[pos-1];
When you are trying to do
arr[pos--] = arr[pos-1];
and the value of pos is 1 then it decrements pos to 0, then in the second usage of pos you are making it 0 - 1
In line 9 your decreasing the counter in the wrong order. The correct line is
`arr[pos] = arr[--pos];`
Here you're swapping the current value in arr[pos] for that in arr[pos-1] as you are decreasing the counter before using it. After, the pos value is already in the correct position to insert the 'temp' value
I have found what the problem is. Step by step execution of the code is here.
Line number 9:
When i == 2, pos == 2. At the line 9 execution order is like this.
At initially first execution if the while loop, arr[2] = arr[pos-1].
Positioning the array index 2. But after positioning pos is decreasing to pos == 1.
Then line becomes to this arr[2] = arr[1-1] means arr[2] = arr[0].
After that still while loop is true.
Then the second execution of the while loop at initially arr[1] = arr[pos-1].
Then positioning the array index 1. But after positioning pos is decreasing to pos == 0.
Then line becomes to this arr[1] = arr[0-1] means arr[1] = arr[-1].
So error happens in here. (ArrayIndexOutOfBounds).
Corrected code is like this. (Line number 9)
arr[pos--] = arr[pos];
or
arr[pos] = arr[--pos];
First of all, keep in mind I am new at this, so smart guys, be nice!
I am trying to understand why in this line:
for(i = word.length() -1; i >= 0; i--)
System.out.print(word.charAt(i));
I get my string replied to me backwards fine (answer: oaiCgiiB), and in this line of code:
for(i = 0 ; i <= word.length(); i++)
System.out.print(word.charAt(i));
I get an error...
Beijing ChicagoException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 15
at java.lang.String.charAt(String.java:646)
at p200548.main(p200548.java:43)
I want the second one to work like the first one but instead of output BiigCiao
Any help would be appreciated.
Because you are out of bounds.
While:
for(i = word.length() -1; i >= 0; i--)
System.out.print(word.charAt(i));
for length = 3, uses the indexes 2, 1, 0, the following:
for(i = 0 ; i <= word.length(); i++)
System.out.print(word.charAt(i));
uses the indexes 0, 1, 2, 3. And 3 is out of bounds for length = 3.
You probably want:
for(i = 0 ; i < word.length(); i++)
System.out.print(word.charAt(i));
which would use the indexes 0, 1, 2.
for(i = 0 ; i <= word.length()-1; i++) //add mines 1 here
System.out.print(word.charAt(i));
you have to add -1 to ;word.length()-1;
because word starts at index "0" and ends with "word.length()-1"
In C language you would not get an exception because it does not care about crossing bounds of an array. This is one of the problems in C. Java, however always checks for bounds and gives you a 'IndexOutOfBoundsException' whenever you try to access an index outside array.
An equivalent code in C:
for(i = 0 ; i <= strlen(word); i++)
printf("%c",word[i]);
would work fine as word[length] is '\0' and there is no problem printing it
I am currently trying to take the elements of an array and reverse its order in Java. How come I cannot print the elements of the array by counting downwards using a for loop without changing the actual ordering of elements in my array?
private void printArray(int[] array) {
for (int i = array.length; i >= 0; i--){
println(array[i]);
}
}
Array indices start at 0 and end at array.length - 1. Here, you get an ArrayIndexOutOfBOundsException since your first read is past the end of the array (int i = array.length;).
Do:
for (int i = array.length - 1; i >= 0; i--)
println(array[i]);
Try
for (int i = array.length - 1; -1 != i; --i){
As indexes start from 0
Im having a bit of a problem with this code each time i execute it it gives me an error
String index out of range: 'n'
n - is the no. of characters that is entered in the textbox pertaining to this code...
(that is textbox - t2.)it is stuck at that first textbox checking it does not go over to the next as mentioned in the array.
Object c1[] = { t2.getText(), t3.getText(), t4.getText() };
String b;
String f;
int counter = 0;
int d;
for(int i =0;i<=2;i++)
{
b = c1[i].toString();
for(int j=0;j<=b.length();j++)
{
d = (int)b.charAt(j);
if((d<65 || d>90)||(d<97 || d>122))
{
counter++;
}
}
}
it is basically a validation code that i am trying to do without exceptions and stuff(still in the process of learning :) )
any help would be appreciated
thx very much.
Use <, not <= when iterating over the string. With <=, you get an out of bounds error, when j equals the length of the string. Remember that characters in the string are indexed starting from zero.
for(int j = 0; j < b.length(); j++)
In java string.charAt(string.length()) will be out of bounds since the string is 0 indexed and so the last character is at string.length() - 1.
Strings are indexed starting at 0. Your second for loop is set to end at b.length, which will always be 1 greater than the highest index for that string., Change it to j < b.length instead.