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.
Related
I want to add some values in string array dynamically by using for loop.
when i debug the code at first for loop it is showing values which are adding.I want to check if any one of the string equals to my given value.but in for loop 2 at index 0 it showing null and at index 1 it showing the string value.
for(int i=0;i<someval;i++) {
String[] mylist = new String[someval];
mylist[i]=previousVal;
System.out.println("Previous Value : " +mylist[i]);
}
for (int j = 0; j <=mylist.length; j++) {
if (mylist[j].equals(givenValue) ) { {
System.out.println("your value found in the array");
}
}
The problem is that you are creating a new array using
mylist = new String...
during each loop iteration.
So, it doesn't really matter if you write something to an array, if the next step consists of throwing that array away.
In other words: make sure that you create the array just once; preferable before entering your loop.
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++)
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' ) {
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.
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
}
}