String index out of range: n - java

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.

Related

String index out of range - Why is this occurring?

(Please keep in mind I have only been studying java for under a month on my own)
I am trying to make a program that simply tells you the last char of the name you give the program. Here is my code:
import java.util.Scanner;
public class LastCharacter {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("hey");
String name = reader.nextLine();
lastChar(name);
}
public static char lastChar(String text) {
char lastChar = '\0';;
int i = 0;
for (i = 0; i <= text.length(); i++) {
lastChar = text.charAt(i);
}
System.out.println(lastChar);
return lastChar;
}
}
Error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at LastCharacter.lastChar(LastCharacter.java:19)
at LastCharacter.main(LastCharacter.java:11)
Java Result: 1
I also know this can be made by subtracting the length of the string by 1, however I would like to know why this method isn't working. I don't really know how to word this but do strings and chars not get along? (pls dont make fun of me)
Thanks!
Java strings start at a base index of 0. Therefore, this line: for (i = 0; i <= text.length(); i++) { is trying to access an index that doesn't exist. The string main only goes from 0 to 3. So, when you try to access index 4, you get the out of bounds error.
Replace this line:
for (i = 0; i <= text.length(); i++) {
With this:
for (i = 0; i < text.length(); i++) { to fix the problem.
The problem is because Java uses a 0 index array for the string. This means that your for loop i <= text.length() is going to the last character +1. In a name like "Joe"
J = 0,
o = 1,
e = 2
The length of "Joe" is 3 and therefor the loop goes to index(3) which is out of the bounds of the character array.
Two things to take note here:
1.) The length() method in Java String class returns the number of characters of a string
2.) Java arrays uses zero-base index
So, to accomplish your task of getting the last character of the name string :
public static char lastChar(String text) {
int textLength = text.length();
char lastChar = text.charAt(textLength - 1); //first char starts from index 0
return lastChar;
}
Hope it helps.
You are out of bounds! The condition should be:
i < text.length()
for (i = 0; i < text.length(); i++) {
lastChar = text.charAt(i);
}
Strings are 0 based, meaning the first index is 0. So for the string "mom", the 0th index is "m", the 1st index is "o" and the 2nd index is "m". That means this string doesn't have a third index, even though its length is 3! Based on that, your loop should be:
for (i = 0; i < text.length(); i++) {
lastChar = text.charAt(i);
}
However, there is an even better way to do it with no loops at all. We can simply get the character at the last index of the string without looping over each character. It is less complicated and more efficent:
lastChar = text.charAt(text.length() - 1);

Finding number of sub strings between two giving chars

I need for my homework to write method that get two parameters, string and char, and it needs to return the number of strings that start with that char and end with that char.
Example:
For the string "abcbcabcacab" and the char 'c', the method will return 6.
(the sub strings are "cbc", "cabc", "cac", "cbcabc", "cabcac", "cbcabcac")
It needs to be as effectiveness as possible, and the only two method that I can use is charAt() and length().This is hard as hell and after 3 hours of trying, I'm asking you guys if there is someone who cal solve this or at least show me some clue.
The obvious solution is to check every symbol in input string and if equals to specified char, then try to find all possible substrings, starting from this point, like this:
long cnt = 0;
for (int i = 0; i < (s.length() - 1); i++)
if (s.charAt(i) == c)
for (int j = (i + 1); j < s.length(); j++)
if (s.charAt(j) == c)
cnt++;
return cnt;
this solution has complexity O(N^2)
but, number of substrings actually determined by number of occurrences of char in string, which appeared to be Triangular number
So, optimized O(N) solution is:
long cnt = -1;
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == c)
cnt++;
return (cnt * (cnt + 1)) >>> 1;
The simplest anwser is that you should use a loop.
Loop through the strings. Check if the current string starts with the given char and ends with the given char. If it doesn't just jump to the next one. if it does just loop with a counter from 1 to length minus the second last char.
You will reduce time by kicking out invalid string and you will be checking 2 chars less EVERY string ;)
I guess that's a quite fast way.
Example
// String definition bla String[] myArray
int count = 0;
for(int i = 0; i < myArray.length(); i++) {
if(myArray[i].charAt(0) == givenChar && myArray[i].charAt(myArray.length()-1)) {
for(int j = 1; j < myArray.length()-2;j++) {
if(myArray[i].charAt(j) == givenChar)
count ++;
}
}
}
That's the rough idea.
I am checking if the given String starts and ends with the givenChar.
If it does im iterating through the string checking for the givenChar again.
If it does exist i am counting 1 up.
I hope that might help your out ;)
Have a nice day!

Java - out of bounds exception

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--)

Recursive word searching to find various versions of a word

I wish to iterate through a word and print out all the different variations of it. I have wrote the code but for some reason i keep on getting an StringIndexOutOfBoundsException.
public class Test {
public static void main(String[] args) {
String word = "telecommunications"; // loop thru this word
for (int i = 0; i < word.length(); i++) {
for (int j = 0; j < word.length(); j++) {
System.out.println(word.substring(i, j + 1));
//This will print out all the different variations of the word
}
}
}
}
Can someone please tell me why I am getting this error?
Remember, arrays are zero-based in Java (and most languages).
This means, that if you have a String of length N, the indexes will be from 0 to N - 1 - Which will have a total sum of N.
Look at this line:
System.out.println(word.substring(i, j + 1));
The length of your string is 18, the indexes are from 0 to 17.
j and i runs on this indexes, but what will happen when you do j + 1 in the last iteration?
- You'll get 17 + 1, which is 18, which is out of bounds.
j | char at j
----+-------------
0 | t
1 | e
... | ...
... | ...
17 | s
18 | :(
I won't tell you the solution, but it's straight forward when you know why this is happening.
The reason for exception is word.substring(i, j + 1).
Suppose, you are iterating through and having i=1 & j=17, in that case you are trying to extract the sub-string starting from position 1 and till i+j+1 = 19th position, whereas you string holds only 18 characters or positions.
I think you want to do something like this
for (int i = 0; i < word.length(); i++) {
for (int j = i; j <= word.length(); j++) { // Change here
System.out.println(word.substring(i, j)); // Change here
//This will print out all the different variations of the word
}
}
You get the exception because when you try to access j+1 with the last index, the index goes out of bounds as the max possible accessible index in any array or arraylist or string is always n-1 where n is the length.
Because word.substring(i, j + 1)
Here j value should be greater than i value. because first two iterations it will work fine.when third iteration i=2 j=0 at that time word.substring(2, 0 + 1) at this condition String index out of range: -1 will come because we cannot go back word substring. second argument should be greater than first argument

Java cannot find symbol for loops, logic problems?

Ok, my program in this specific section takes a line of data from a studentAnswer string array, the value of which would be something like TTFFTFTFTF. I am supposed to take this, and compare it against a key array, which might look like TFFFTFTFTF. A student takes a quiz, and my program calculates the points correct.
My intention is to use a separate points array to find the numeric grade for the student. The index of studentAnswer refers to a specific student. So studentAnswer[i] is TTFFTFTFTF. I use substrings to compare each individual T/F against the correct answer in key[], which would have a single T/F in each index. Then, if they are correct in their answer, I add a 1 to the correlating index in points[] and will later find the sum of points[] to find the numeric grade out of ten.
My problem here is that String origAns, used to define the student's original answer string, is getting a Java Error cannot find Symbol. I have tried placing the instantiation of origAns within each different for loop, but I can't get the program to work. Int i is meant to follow each specific student- I have four parallel arrays that will all log the student's ID number, numeric grade, letter grade, and original answers. So that is the intention of i, to go through each student. Then j should be used to go through each of these original student answer strings and compare it to the correct answer...
Logically, it makes sense to me where I would put it, but java doesn't agree. Please help me to understand this error!
for (int i = 0; i < studentAnswer.length; i++){
String origAns = studentAnswer[i];
for (int j = 0; j < key.length; j++){
if (origAns.substring[j] == key[j]){
//substring of index checked against same index of key
points[j] = 1;
}
if (origAns.substring[j] != key[j]){
points[j] = 0;
}
}
}
It sounds like you're trying to call the substring method - but you're trying to access it as if it were a field. So first change would be:
if (origAns.substring(j) == key[j])
Except that will be comparing string references instead of contents, so you might want:
if (origAns.substring(j).equals(key[j]))
Actually, I suspect you want charAt to get a single character - substring will return you a string with everything after the specified index:
if (origAns.charAt(j) == key[j])
... where key would be a char[] here.
You can also avoid doing the "opposite" comparison by using an else clause instead.
You should also indent your code more carefully, for readability. For example:
for (int i = 0; i < studentAnswer.length; i++) {
String origAns = studentAnswer[i];
for (int j = 0; j < key.length; j++) {
if (origAns.charAt(j) == key[j]) {
points[j] = 1;
} else {
points[j] = 0;
}
}
}
And now, you can change that to use a conditional expression instead of an if/else:
for (int i = 0; i < studentAnswer.length; i++) {
String origAns = studentAnswer[i];
for (int j = 0; j < key.length; j++) {
points[j] = origAns.charAt(j) == key[j] ? 1 : 0;
}
}
When you call a method in Java, you use parentheses () instead of brackets [].
Since substring is a method, you should call it like so
if (origAns.substring(j) == key[j])
A few other notes, you should use the equals method for comparisons (especially those comparisons involving Strings.)
if (origAns.substring(j).equals(key[j]))
Also, you should use charAt to extract a single character at some position in a string. substring(j) will return a string of characters starting at position j.
if (origAns.charAt(j).equals(key[j]))
Your explanation is very long and I have not read it from the beginning to end. But I can see at least one problem in your code:
if (origAns.substring[j] == key[j])
You are comparing strings using == instead of using method equals():
if (origAns.substring[j].equals(key[j]))
Substring is a function, not a member, of String objects. Check out the example at the top of this page:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
Notice the use of parenthesis instead of brackets.
If you are using a String use charAt function
String studentAnswer = "TTFFTFTFTF";
for (int i = 0; i < studentAnswer.length(); i++)
{
char origAns = studentAnswer.charAt(i);
}
Else if you are using an char array then
char studentAnswer[] = "TTFFTFTFTF".toCharArray();
for (int i = 0; i < studentAnswer.length; i++){
char origAns = studentAnswer[i];
}

Categories

Resources