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
Related
I have tried using below code, though it works but does not satisfy the requirement.Please share your knowledge , Thanks
String temp;
for(int i = 0; i < lexicon.size(); i++)
{
for (int j = lexicon.size() - 1; j > i; j--)
{
if (lexicon.get(i).compareTo(lexicon.get(j)) > 0)
{
temp = lexicon.get(i);
lexicon.set(i,lexicon.get(j)) ;
lexicon.set(j,temp);
}
}
}
ArrayList<String> uniqueWords = new ArrayList<String>();
for(int i = 0; i < lexicon.size(); i++) //Removing duplicates
{
int wordCount = 1;
uniqueWords.add(lexicon.get(i));
for(int j = i+1; j < lexicon.size(); j++)
{
if(uniqueWords.get(i).equals(lexicon.get(j)))
{
wordCount++;
lexicon.remove(j);
}
}
System.out.println(uniqueWords.get(i) + " " + wordCount);
}
This is the output i am getting:
a 6
a 3
a 2
about 1
acknowledged 1
all 1
also 1
and 2
answer 1
at 2
austen 1
be 2
been 1
bennet 2
bennet 1
I need something like this: Word Count for that word
a 11
about 1
acknowledge 1
and so on
The problem is that you are removing elements from your lexicon at lexicon.remove(j); and also moving forward in your lexicon with your check at lexicon.get(j)
I don't want to give you the full code that works, because you won't learn anything from that, but I hope I gave you enough hint, to solve your problem. Try debugging your code, and see what happens with the variables :)
On removal at index j, j get's increased by j++, actually skipping one, where it should have continued without increasing.
As already sorted:
String word = uniqueWords.get(i);
int j = i+1;
while (j < lexicon.size() && word.equals(lexicon.get(j)))
{
wordCount++;
lexicon.remove(j);
}
(I'll give the code, as it shows a somewhat different approach.)
I have a basic question about the inner loop length in Java selection sort. Here is the commonly used code for selection sort:
package com.java2novice.algos;
public class MySelectionSort {
public static int[] doSelectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int index = i;
for (int j = i + 1; j < arr.length; j++)
/* why not the length is not arr.length-1? I think the length is
exactly the same as what it is, the array's length is a
static number as array.length-1, but when it comes to the inner
loop why it plus 1 to the array length? */
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
}
Imagine you're trying to sort five items. The array length is 5, which means the indexes are 0 through 4.
In the first iteration of the inner loop, you have i=0 and j=1. You need j to index to the end of the array. That's why the expression in the inner loop is j < array.Length.
i, of course, only goes from 0 to 3, which is why the outer loop has i < array.Length - 1.
If you lay five playing cards on a table and walk through the steps of the selection sort, you'll get a better idea of what's happening here.
the first loop does not need to check the last index, therefore, it goes to arr.length - 1. on the second loop, of course, the last index of the array must be checked so the loop goes to the last index (arr.length).
imagine if the first loop goes to the last index. then this line for (int j = i + 1; j < arr.length; j++) will never execute.
check out this Pseudo code of selection sort for a better understanding of the algorithm
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 don't know how to address the question properly to even google it so far.
In a nested loop such as this
for (int i=0;i>0;i++)
{
for(int k=0;k<0;k++)
{
}
}
What kind of applications would there be if we use k
I have this question because I wanted to make a loop which iterates like star printing with * char printing left triangle but it iterates on a 2 dimensional matrix as the cursor moves it iterates on the array items such as this
a[0][0]
a[1][0], a[1][1]
a[2][0], a[2][1], a[2][2]
a[3][0], a[3][1], a[3][2], a[3][3]
I want to figure out a for loop or something to be able to iterate the array such as this. What do you suggest?
You must change the first for condition, because when i = 0 the condition i > 0 is false, so it never enters the loop.
Note that when you go line be line, the k must iterate in this pattern: [0, 01, 012, 0123] while i in [0, 1, 2, 3]. In other words, k must iterate until it reaches the value of i, so the condition of the nested for must be k < i + 1.
for (int i = 0; i < 4; i++) {
for (int k = 0; k < i + 1; k++) {
// Here you should access to the array
// array[i][k]
System.out.print(i + " " + k + " - "); // [DEBUG]
}
System.out.println(); // [DEBUG]
}
Output: Just to see indexes
0 0 -
1 0 - 1 1 -
2 0 - 2 1 - 2 2 -
3 0 - 3 1 - 3 2 - 3 3 -
It looks like what you want is something like
for (int i = 0; i < SOME_LIMIT; ++i) {
for (int k = 0; k <= i; ++k) {
do_something_with (a[i][k]);
}
}
It looks like you've already done the hard part -- designing the basic premise of the application and writing down on paper what you'd like to do.
Now all you do is take what you've written down and translate it in to code.
I'll give you one hint. On the inside loop, for(int k=0;k<0;k++), thibnk about how you would change this in order to achieve the behavior you're looking for.
Keep at it, you'll get there. The hard part is already done.
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.