There last 2 days I am 100% brain dead and cant find where the error is... Can anyone give me a tip >>
for(String inputString : word)
{
StringBuilder sb = new StringBuilder(inputString);
if(inputString.charAt(inputString.length()-1) == ']')
{
sb.deleteCharAt(inputString.length());
}
else if(inputString.charAt(0) == '[')
{
sb.deleteCharAt(0);
}
breaker.add(sb.toString());
}
It was suppose to be a simple function to remove the [ ] characters from a string but everytime I run it I get
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
But only on the third or fourth pass never the first or second.
Confused.
sb.deleteCharAt(inputString.length());
should be
sb.deleteCharAt(inputString.length() - 1);
Because you want to remove the last character (you did it correctly in the test!)
You're deleting the last char at the StringBuilder's length, rather than length - 1.
StringBuilder, not unlike all String and array representations in Java, is 0-indexed.
Use the following idiom instead:
sb.deleteCharAt(sb.length() - 1);
The reason why the StringIndexOutOfBoundsException is only thrown arbitrarily in your execution is likely because of the condition checking for the ] character, which may not always hold true (hence the offending code would not execute).
Related
So this is my code in Java (for returning two halves of a string - one is the odd half, starting with the index 0, or the first character, and the second half, starting with the index 1, or the second character):
public class StringTest{
public String halfOfString(String message, int start){
int length = message.length();
StringBuilder output = new StringBuilder(length);
char ch;
int i;
if((start==0)||(start==1)){
for(i=start; i<message.length(); i=i+2){
ch = message.charAt(i);
output.setCharAt(i,ch); // error occurs here
}
}
return output.toString();
}
public void testFunction(){
String s = "My name is Sid";
String first = halfOfString(s, 0);
String second = halfOfString(s, 1);
System.out.println("First half is " + first + " and second half is " + second);
}
}
So my problem is - whenever I attempt to run this program on BlueJ IDE, it doesn't, and returns the error in the title, on the line mentioned in the comment.
I have poured over this site for a similar question which may help me with my error, but all I found was a question which suggested a change I have already implemented (in the StringBuilder setCharAt method, the person had reversed the i and ch parameters).
Is it anything to do with the fact that the "output" is declared empty at first, and the setCharAt method can only replace the characters which already exist?
Any help would be greatly appreciated.
Is it anything to do with the fact that the "output" is declared empty at first, and the setCharAt method can only replace the characters which already exist?
Yes, that is exactly why you get this error.
Note that creating a StringBuilder with a specified length, as you are doing:
StringBuilder output = new StringBuilder(length);
does not create a StringBuilder which already has that many characters - it just creates a StringBuilder with that internal buffer size. The StringBuilder itself still contains no characters, so trying to set the first character will result in the exception that you get.
Call append on the StringBuilder to add characters instead of setCharAt.
Is it anything to do with the fact that the "output" is declared empty
at first, and the setCharAt method can only replace the characters
which already exist?
Yes, that's the reason.
The Javadoc of setCharAt is clear on this:
The index argument must be greater than or equal to 0, and less than
the length of this sequence.
Why don't you just use the append method in StringBuilder? It looks to me like, if your code would work, it would leave holes in the StringBuilder since you're only setting every other character and not the ones in between. Using append ensures that there are no holes.
I have some problems with the code every time I try to compile the exception java.lang.StringIndexOutOfBoundsException appears. Here is the code with the problem I really don't know what I have done wrong. In the code I try to split a string using some conditions, the string represent a polynomial.
int[] coef1= new int[20];
for(i=0;i<polinom.length()+1;i++){
if(polinom.charAt(i)=='+' )
c=polinom.charAt(i+1);
else{
if(polinom.charAt(i)=='^'){
v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
coef1[v]=Integer.parseInt(Character.toString(c));
System.out.print(coef1[v]);
}
}
}
for(i=0;i<polinom.length()+1;i++){
if(polinom.charAt(i)=='-' )
c=polinom.charAt(i+1);
else{
if(polinom.charAt(i)=='^'){
v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
coef1[v]=-Integer.parseInt(Character.toString(c));
System.out.print(coef1[v]);
}
}
}
The exception is here if(polinom.charAt(i)=='+' )
Just replace all your
for(i=0;i<polinom.length()+1;i++){
with
for(i=0;i<polinom.length()-1;i++){
As indices are 0-based and you use polinom.charAt(i+1), i+1 should never be equal (nor greater) than polinom.length.
Or if you want ot be able to test until the last character of you string (for other processing), you can ensure that polinom.charAt(i+1) gets never triggered if i == polinom.length() - 1, just add a test before processing your stuff:
for(i=0;i<polinom.length();i++){ // not using -1, looping to the end of the string
if(polinom.charAt(i)=='+' && i < polinom.length() - 1) // checking that no exception will be thrown
c=polinom.charAt(i+1);
else{
if(polinom.charAt(i)=='^' && i < polinom.length() - 1){ // same
v=Integer.parseInt(Character.toString(polinom.charAt(i+1)));
coef1[v]=-Integer.parseInt(Character.toString(c));
System.out.print(coef1[v]);
}
}
}
In the second line here you are using
for(i=0;i<polinom.length()+1;i++){
That +1 should be -1.
I suppose the variable polinom is a String.
Your're looping beyond the end of the string:
for(i=0;i<polinom.length()+1;i++)
It should be
for(i=0;i<polinom.length()-1;i++)
I'm simply trying to delete the last char in a String, I know this is a simple task and has been done any times BUT for some reason it doesn't work.
Example method
public String removeLastChar(String stringToRemoveCharFrom)
{
if(stringToRemoveCharFrom.length() > 0)
{
return stringToRemoveCharFrom.substring(0, stringToRemoveCharFrom.length());
}
else{
return stringToRemoveCharFrom;
}
}
Now, when I output the string sometimes I get an empty char at the end, when I call this function it runs the correct way BUT the string stays the same.
Debugger shows:
\b in some of the outputs, what is this? And how do I avoid it?
Any ideas?
I replaced the end with -1 like in the answers but it still fails to delete:
return stringToRemoveCharFrom.substring(0, stringToRemoveCharFrom.length() - 1);
It seems for some reason JAVA is entering weird characters that cannot be deleted. such as \b.
If I do the following at the start:
stringToRemoveCharFrom = stringToRemoveCharFrom.replaceAll("\b", "");
it works. But I'm wondering what this char is?
stringToRemoveCharFrom.substring(0, stringToRemoveCharFrom.length())
will return the entire String. What you should be doing is:
stringToRemoveCharFrom.substring(0, stringToRemoveCharFrom.length() - 1)
This is because substring(int start, int end) returns a substring starting at "start", and ending at the index 1 before "end". The starting index is inclusive, the end is exclusive.
You forgot to subtract one from the length:
public String removeLastChar(String stringToRemoveCharFrom)
{
if(stringToRemoveCharFrom.length() > 0)
{
return stringToRemoveCharFrom.substring
(0, stringToRemoveCharFrom.length() - 1);
}
else{
return stringToRemoveCharFrom;
}
}
stringToRemoveCharFrom.substring(0, stringToRemoveCharFrom.length());
Is a copy of the string, if you want to strip the last character, use:
stringToRemoveCharFrom.substring(0, stringToRemoveCharFrom.length() - 1);
I have a method which takes a string parameter and split the string by # and after splitting it prints the length of the array along with array elements. Below is my code
public void StringSplitTesting(String inputString) {
String tokenArray[] = inputString.split("#");
System.out.println("tokenArray length is " + tokenArray.length
+ " and array elements are " + Arrays.toString(tokenArray));
}
Case I : Now when my input is abc# the output is tokenArray length is 1 and array elements are [abc]
Case II : But when my input is #abc the output is tokenArray length is 2 and array elements are [, abc]
But I was expecting the same output for both the cases. What is the reason behind this implementation? Why split() method is behaving like this? Could someone give me proper explanation on this?
One aspect of the behavior of the one-argument split method can be surprising -- trailing nulls are discarded from the returned array.
Trailing empty strings are therefore not included in the resulting array.
To get a length of 2 for each case, you can pass in a negative second argument to the two-argument split method, which means that the length is unrestricted and no trailing empty strings are discarded.
Just take a look in the documentation:
Trailing empty strings are therefore not included in the resulting
array.
So in case 1, the output would be {"abc", ""} but Java cuts the trailing empty String.
If you don't want the trailing empty String to be discarded, you have to use split("#", -1).
The observed behavior is due to the inherently asymmetric nature of the substring() method in Java:
This is the core of the implementation of split():
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
The key to understanding the behavior of the above code is to understand the behavior of the substring() method:
From the Javadocs:
String java.lang.String.substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring
begins at the specified beginIndex and extends to the character at index
endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Examples:
"hamburger".substring(4, 8) returns "urge" (not "urger")
"smiles".substring(1, 5) returns "mile" (not "miles")
Hope this helps.
Hey guys I was hoping someone could explain to me the error in this code? I'm just having a little trouble understanding why it's throwing that exception.
The first condition checks for the minimum length of string which should be 3. So "bad" and "xba" passes the first condition.
Lets go with bad first.
The second condition has two OR clauses and string "bad" satisfies the first of two OR clauses at line no 3. And hence the answer is TRUE
Now with xba..
The first of two OR clauses fails, so it checks for the second one. And here str.substrin(1, 4) throws StringIndexOutOfBoundsException as the number of character in the String xba is only 3.
I would simple do a STRING.regionMatches() as below
String testString = "bad";
String givenString = "xxbad";
boolean zeroIndexMatch = givenString.regionMatches(true, 0, testString, 0, 3);
boolean firstIndexMatch = givenString.regionMatches(true, 1, testString, 0, 3);
if (zeroIndexMatch || firstIndexMatch) {
System.out.println(true);
} else {
System.out.println(false);
}
The tested String "xba" has the length 3 with the indices from 0 to 2.
Your second method call of substring is str.substring(1,4). Therefore it tries to read the indices 1 till 3 (the endIndex 4 is exclusive). So you're trying to read from index 3, but since the String isn't long enough to have such index, you're getting the mentioned Exception.
When you are using the str.substring(1, 4) method it is causing a problem with that 7th test because it is only using a string that is 3 characters long. By trying the access that fourth character you are going out of the string's bounds, and therefore getting the StringIndexOutOfBoundsException.