String index out of bounds? Where? - java

This is my code for finding the no. of vowels in a string:
{
String inyo=inpeo.getText().toLowerCase();
System.out.println(inyo); // Just checking for an empty string
int vowcount=0;
for(int i=0;i<=inyo.length();i++)
{
char rol=inyo.charAt(i);
if(rol=='o'||'u'==rol||rol=='a'||rol=='e'||rol=='i')
{
vowcount=vowcount+1;
System.out.println(vowcount);
}
numout.setText(""+vowcount);
}
}
Now, nothing is wrong with the output here-it finds the exact no. of vowels as I intended. But it gives me this error:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:646)
at WordCheck.jButton2ActionPerformed(WordCheck.java:147)
// Extra errors removed as they're irrelevant to my issue
As a result, there is no way of reusing the program other than closing and restarting it. when the output is coming out as desired, why am I getting this error? I don't get any empty Strings, either.

The last iteration of the for loop is causing the exception (when i == inyo.length()). Simply replace it with:
for(int i=0; i<inyo.length(); i++)

i<=inyo.length() here. The String index starts from 0. The length count starts from one. So, the last index of a String is 4 when its length is 5.
It should be
i<inyo.length()

Your for loop is going one too far, this
for(int i=0;i<=inyo.length();i++)
should be
for(int i=0;i<inyo.length();i++)
Note that when i == invo.length() it's passed the end of the array, because Java starts indexing with 0.

The for loop should be
for(int i=0; i<inyo.length(); i++)
Presently when it goes to the last iteration the index of the string is 4 whereas inyo.length() is 5. Hence it results in out of bounds.

Related

My 'for loop' inside another 'for loop' is not working

for (int i=0; i<Intlength; i++){
int intPosition;
intPosition=strAlphabet.indexOf(strMessage.charAt(i));
System.out.println(intPosition);
System.out.println("BREAK");
for (int k=0; k<Intlength2; k++){
int intPosition2;
intPosition2=strAlphabet.indexOf(strKeyword.charAt(k));
System.out.println(intPosition2);
System.out.println("BREAK-------------");
}
}
i will ask the user to type in two words. one is a message and one is a keyword.
the first loop above will check that if i
will add 1, and print out the first letters position number. for example if the message was "red". i would first want it to output the position number of "r" which is 17. then it mmust move to the second loop, and do the exact same for the keyword. for example if the keyword was "cat" i would want it to print the first letter position of the first letter in this case "c" has the position value of 2. in this way i want the output to be as such:
first letter position of message
first letter position of keyword
second letter position of message
second letter position of keyword
etc.
therefore sticking to the message "red" and the keyword "cat" i would want the output as such:
17
2
4
0
3
19
i have added in break texts to distinguish what was happening to my coding and this was the result.
Please give me a message:
red
Thank you! Now please give me a keyword:
cat
17
BREAK
2
BREAK-------------
0
BREAK-------------
19
BREAK-------------
4
BREAK
2
BREAK-------------
0
BREAK-------------
19
BREAK-------------
3
BREAK
2
BREAK-------------
0
BREAK-------------
19
BREAK-------------
as you can see it putputs the first letter position of the message, then all three positions of the keyword, and goes onto the second position letter of the message then again outputting all three position values of the keyword.
how do i fix this to get the output i want, i am sure that i am not writing the forloop correctly.
What you've got are nested for loops to make it do what you suggested they just need to be one after the other, not nested inside each other. When you put the second for loop inside the first what you're telling it to do is print each letter in the keyword for every letter in the message.
What you want is a loop like this (It's unclear what you want it to do if one string is longer than the other, I'm assuming you want it to stop with the shorter string but you can change that.)
if(strMessage.length > keyword.length){
intLength = keyword.length;
} else {
intLength = strMessage.length;
}
for (int i=0; i<intLength; i++){
//Print the position of the i'th letter of the message
int intPosition;
intPosition=strAlphabet.indexOf(strMessage.charAt(i));
System.out.println(intPosition);
//Print the position of the i'th letter of the keyword
int intPosition2;
intPosition2=strAlphabet.indexOf(strKeyword.charAt(i));
System.out.println(intPosition2);
}
When you nest loops, the inner one is executed from start to end for each iteration of the outer loop.
You probably need something like that (note that there's only one loop):
for (int i=0; i < Math.max(strMessage.length, keyword.length); i++){
if (i < strMessage.length) {
System.out.println(strAlphabet.indexOf(strMessage.charAt(i)));
} else {
// To be defined
}
if (i < strKeyword.length) {
System.out.println(strAlphabet.indexOf(strKeyword.charAt(i)));
} else {
// To be defined
}
}
(NB: not tested, not compiled)
If you break your requirement, you will get to know that you have straight forward functionality of taking a character at a given index from your both the string.
So you only need single for loop. Inside that you can take character from first string and then from second string.
Note: You need to take care of length of both the strings. Depending on it you can fetch the character from it.
Another Approach without IF else block
for (int i=0; i<Math.max(strMessage.length, keyword.length);i++){
int intPosition;
try{
intPosition=strAlphabet.indexOf(strMessage.charAt(i));
System.out.println(intPosition);
}catch(Exception e){
}
try{
intPosition=strAlphabet.indexOf(strKeyword.charAt(i));
System.out.println(intPosition);
}catch(Exception e){
}
}
String strAlphabet="ABCDEFGHIJKLMNOPQRSTUWXYZ";
String strMessage="red".toUpperCase();
String strKeyword="cat".toUpperCase();
int Intlength=strMessage.length();
int Intlength2=strKeyword.length();
for (int i=0; (i<Intlength) || (i<Intlength2); i++){
int intPosition=strAlphabet.indexOf(strMessage.charAt(i));
System.out.println(intPosition);
int intPosition2=strAlphabet.indexOf(strKeyword.charAt(i));
System.out.println(intPosition2);
}
1) Make the comparison case-insensitive. Don't be sure that user will take care of case while typing words.
2) Ensure the expected behavior in case message length is shorter than keyword or vice versa.

How to check the end of args array?

I am writing a parser program in Scala that should read input using "args" and pars it. It doesn't matter I use:
while(!args.isEmpty){
if (Files.exists(Paths.get(args(j)))){
Statement=Statement.concat(inputXml)
Statement=Statement.concat(" ")
println(j)
}
else{
Statement=Statement.concat(args(j))
Statement=Statement.concat(" ")
println(j)
}
j=j+1
}
or
while(args.length !=0) {
if (Files.exists(Paths.get(args(j)))){
Statement=Statement.concat(inputXml)
Statement=Statement.concat(" ")
println(j)
}
else{
Statement=Statement.concat(args(j))
Statement=Statement.concat(" ")
println(j)
}
j=j+1
}
The program gives me run time exception of array index out of bound! sending 2 values as input:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
what should I do? I am confused!
Your exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
Is because you are not breaking the while loop; the args parameter never change it's size, so your while will go forever util j exceed the size of args.
Maybe you could try:
int i = 0
while (i < args.length){
// some code here
i++;
}
or
for(int i = 0; i < args.length; i++){
// some code here
}
If you want to iterate through all the array
From what you describe, you need to iterate through your array while your index is lower than the maximum array size. If you merely compare args.length value, the loop condition will continue to evaluate to a truth value infinitely, since args.length will always be different than 0 (if not changed).
You need something along the lines of:
for(i <- 0 until array.length){
...
You can find extra information on accessing and iterating over arrays here and here
Consider iterating over args without using indexed references (the source of out-of-bounds error),
for ( arg <- args ) yield {
if (Files.exists(Paths.get(arg))) xmlFile
else ""
}.mkString(" ")
This for comprehension yields a collection of String which is converted to a space-separated string with mkString.

Out of Bounds Exception on a 2D Ragged Array in Java

Problem solved, I ended up need a seperate counter for the array position. Thanks for the help!
I'm writing a small app that takes a string, processes each string into 7-bits of binary code and then fills in a musical scale based on the string. For instance, if I had the binary 1000100, in the key of C Major that would give me the notes C and G(C 0 0 0 G 0 0).
I'm having an issue with a specific piece of code that takes an input of String[] (in which each element is a single character worth of binary, 7-bits) and processes each individual character in the strings themselves and stores the index number of where 1's occur in the string. For example, the string 1000100 would output 1 and 5.
Here's the method that does that:
public static String[][] convertToScale(String[] e){
String[][] notes = new String[e.length][]; //create array to hold arrays of Strings that represent notes
for(int i = 0; i < e.length; i++){
notes[i] = new String[findOccurancesOf(e[i])]; //create arrays to hold array of strings
for(int x = 0; x < e[i].length(); x++){
if((e[i].charAt(x)) != 48){ //checks to see if the char being evaluated is 0(Ascii code 48)
notes[i][x] = Integer.toString(x + 1); // if the value isn't 0, it fills in the array for that position.the value at x+1 represents the position of the scale the note is at
}
}
}
return notes;
}
Here is the code that is uses to get the occurrences of 1 in e[1]:
public static int findOccurancesOf(String s){
int counter = 0;
for(int i = 0; i < s.length(); i++ ) {
if( s.charAt(i) == 1 ) {
counter++;
}
}
return counter;
}
The issue I'm having is with the convertToScale method. When using "Hello world" as my input(the input gets converted into 7-bit binary before it gets processed by either of these methods) it passes through the 2nd for-each loop just fine the first time around, but after it tries to fill another spot in the array, it throws
java.lang.ArrayIndexOutOfBoundsException: 3
EDIT:It occurs in the line notes[i][x] = Integer.toString(x + 1); of the convertToScale method. I've run the debugger multiple times through after trying the proposes changes below and I still get the same error at the same line. The findOccurancesOf method returns the right value(When evaluating H(1001000) it returns 2.) So the thing that confuses me is that the out of bounds exception comes up right when it fills the 2nd spot in the array.
Also, feel free to tell me if anything else is crazy or my syntax is bad. Thanks!
In findOccurancesOf():
if( s.charAt(i) == 1 ) { should be if( s.charAt(i) == '1' ) { to check for the character '1'.
Otherwise it's looking for the character with ASCII value 1.
There is an out of bounds exception because if findOccuranceOf() returns the wrong value, then notes[i] is not constructed with the correct length in the following line of convertToScale():
notes[i] = new String[findOccurancesOf(e[i])];
In addition, you probably want to use something like:
notes[i][c++] = Integer.toString(x + 1);
with some counter c initialized to 0, if I understand your intentions correctly.
The reason for AIOOBE lies in this line:
notes[i] = new String[findOccurancesOf(e[i])]; //create arrays to hold array of strings
Where you call findOccurancesOf method to find occurance of 1 in your String say Hello which you dont find and return 0 and then you call notes[i][x] = Integer.toString(x + 1); with x as 0. Now since you never allocated space, you get array index out of bound exception.
I would suggest the folowing:
Validate your string before assigning the index say to be greater than 0 or something.
Initialize you notes[i] as notes[i] = new String[e[i].length];
Checking character with single quotes like a == '1' rather than a == 1
The exception is caused by what almas mentioned, note however, that your logical error is most likely inside findOccurencesOf method, if the idea was to find all the '1' chars inside a string you must change to what I outlined below, note the apostrohes. Otherwise a char is getting converted to a byte ascii code, and unless matched with a code of ascii code one, the method will return 0, causing your exception
if( s.charAt(i) == '1' ) {

Index-out-of-bound exception in java

Exception messages:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
Following is the code I am using to highlight specific words in JTextPane. My objective is to create a simple syntax highlighting editor, I have searched thoroughly about it and have found many interesting solutions but I wanted to write my own code for it and now I am stuck on an IndexOutOfBoundsException.
My editor gives this exception whenever third key is pressed , meaning whenever 2 letters are written in the JTextPane.
My apologies if the code is not easily understandable, I am new at learning conventions.
I know this is a very trivial question but any sort of help would be considerable.
Thank you :)
[Update] The first part of the code works on the jTextPane2KeyTyped event
String[] words = new String[] {"if","else","for"};
//words is the list for words to change color
StyledDocument doc = jTextPane2.getStyledDocument();
Style style=doc.addStyle("Red_Colour", null);
StyleConstants.setForeground(style, Color.RED);
StyleConstants.setForeground(common,Color.BLACK);
String temp = jTextPane2.getText();
//temp holds the string value of the text present in the jTextPane2
int check=0;
for(int i=0;i<temp.length();i++){
for(int j=0;j<words.length;j++){
if(charLeft(temp,words,i,j)){
if(temp.length()>=words[j].length())
for(int k=0;k<words[j].length();k++){
if(temp.charAt(i+k)==words[j].charAt(k))check++;
}
//else{break;}
if(check==words[j].length()){
doc.setCharacterAttributes(i,words[j].length(),style, false);
}
}
}
}
Following is the code for the method called(i.e. charLeft())
public Boolean charLeft(String temp,String[] words,int i,int j){
temp= temp.substring(i, temp.length());
if(temp.length()<words[j].length())return true;
else return false;
}
TrackBack for the exceptions
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at NewJFrame.jTextPane2KeyTyped(NewJFrame.java:164)
at NewJFrame.access$000(NewJFrame.java:24)
at NewJFrame$1.keyTyped(NewJFrame.java:59)
at java.awt.Component.processKeyEvent(Component.java:6460)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2828)
at java.awt.Component.processEvent(Component.java:6282)
...
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at NewJFrame.jTextPane2KeyTyped(NewJFrame.java:164)
at NewJFrame.access$000(NewJFrame.java:24)
at NewJFrame$1.keyTyped(NewJFrame.java:59)
at java.awt.Component.processKeyEvent(Component.java:6460)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2828)
...
You're actually incrementing j in the third loop as well, instead of k:
if(temp.length()>=words[j].length())for(int k=0;k<words[j].length();j++)
A spontaneous guess would be that you should change it to the following, to avoid exceeding the max length:
if(temp.length()>=words[j].length())for(int k=0;k<words[j].length();k++)
I think that this line might be your problem (This is line 3 of the second code block you posted):
if(temp.length()>=words[j].length())for(int k=0;k<words[j].length();j++){if(temp.charAt(i+k)==words[j].charAt(k))check++;}
You actually increment j instead of k here:
for(int k=0;k<words[j].length();j++)
And because j corresponds to words.length (which is 3) when you type the third character it tries to reference words[3] which does not exist. I would suggest changing it to:
for(int k=0;k<words[j].length();k++)
Hope that helps.
Edit:
Now I am thinking that instead of saying:
if(temp.charAt(i+k)==words[j].charAt(k))check++;
You might want to say:
if(temp.charAt(i)==words[j].charAt(k))check++;
Fixed! The problem was that I was not changing the value of count back to zero. Other problem was in the conditional operator in charLeft() , which was
if(temp.length()<words[j].length())return true;
Corrected condition is
if(temp.length()>=words[j].length())return true;

Finding index of an array while only knowing half the value

sender.sendMessage("Your referal code is: " + codestring[ArrayUtils.indexOf(namestring, value )]);
the value is equal to "name" plus a random number, how can i make this work without knowing the second part of this string array?
iterate through array and check for startsWith()
for(int index = 0 ; index < array.length ; index ++){
if(array[index].startsWith(key)){return index;}
}
return -1; // not found
I didn't understand what you asked, but if you're trying to find a String, knowing only the first characters, you might use a regular expression to check, like:
for(String string: arrayOfStrings){
if(string.matches("beginningOfString^[1-9]")){
// your code
}
}

Categories