java.lang.ArrayIndexOutOfBoundsException: length=1; index=2 caused by IF condition - java

Good day everyone
Im creating application and I need to get some data from text. For this reason i was creating Arraylist, which will be filled up by needed data, was from splitted before string "gh2[]".I was using IF condition to determine required data(gh2[i].matches("[0-9]+]). After filling Array, I was converting Array to a string, by StringBuilder, after this string was splitted.
My problem is when I want to call back for examble second value from splitted String Im getting this error: java.lang.ArrayIndexOutOfBoundsException: length=1; index=2.
I dont understand reason of this error becouse when Im checking, size of the Array is showing 23, when Im calling back string before splitting I can see that is filled up by required data. I was trying to change IF condition like for examble giving negation, then everything is working fine but Array is not filled up by data which I need. Please for advice how to fix this problem. gh2 This my
Here is my program, this is my first program in Android Studio.
ArrayList<String> listawynikow = new ArrayList<String>(gh2.length);
for (int i = 0; i < gh2.length; i++) {
if (gh2[i].matches("[0-9]+")) {
listawynikow.add(gh2[i]);
}
}
StringBuilder sb2 = new StringBuilder();
for (int j = 0; j < listawynikow.size(); j++) {
sb2.append(listawynikow.get(j)).append(";").append("\n");
}
String wyniki1 = sb2.toString();
String[] WYNIKI = wyniki1.split(";");

OK, finally I fix the problem by this.
for(i2=0; i2<gh2.length;i2++) {
listawynikow.add(gh2[i2]); }
for(int j2=0; j2<listawynikow.size();j2++){
if (!gh2[j2].matches("[0-9]+")){
listawynikow.remove(gh2[j2])
Thanks everybody for help and fingers crossed for my problem.

Related

BubbleSort for Object type of array is not working perfectly

I want to ask about bubblesort (Java)
Here's my code
Object[] bubbled = {"LMAO", 3.48 ,2.3 ,3.61 ,3.16 ,3.56 ,2.9 ,3.99 ,4.87 ,3.91};
for(int pass=1 ; pass<bubbled.length-1;pass++){
for(int i=1;i<bubbled.length-1-pass;i++){
if(Double.parseDouble(String.valueOf(bubbled[i]))>
Double.parseDouble(String.valueOf(bubbled[i+1]))){
float hold= Float.parseFloat(String.valueOf(bubbled[i]));
bubbled[i] = bubbled[i+1];
bubbled[i+1] = hold;
}
}
}
The array is Object[] type. and I want it to start at bubbled[1] since bubbled[0] is non-numeric value.
It does the sorting but not to my last 3 index at the end of the process.
For example:
Before : 3.48 ,2.3 ,3.61 ,3.16 ,3.56 ,2.9 ,3.99 ,4.87 ,3.91
After : 2.3 ,2.9 ,3.16,3.48 ,3.56, 3.61 ,3.99, 4.87 ,3.91
Can someone please point out what's wrong ?
You're not making enough passes over the array.
for(int pass = 0; pass < bubbled.length; pass++){
Your code is correct but you forgot the last iteration in each for loop.
change your for loops to:
for(int pass=1 ; pass<bubbled.length;pass++){
for(int i=1;i<bubbled.length-pass;i++){
and that should work just fine

Null Pointer that makes no sense to me?

Im currently working on a program and any time i call Products[1] there is no null pointer error however, when i call Products[0] or Products[2] i get a null pointer error. However i am still getting 2 different outputs almost like there is a [0] and 1 or 1 and 2 in the array. Here is my code
FileReader file = new FileReader(location);
BufferedReader reader = new BufferedReader(file);
int numberOfLines = readLines();
String [] data = new String[numberOfLines];
Products = new Product[numberOfLines];
calc = new Calculator();
int prod_count = 0;
for(int i = 0; i < numberOfLines; i++)
{
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
if(data[i].contains("input"))
{
continue;
}
Products[prod_count] = new Product();
Products[prod_count].setName(data[1]);
System.out.println(Products[prod_count].getName());
BigDecimal price = new BigDecimal(data[2]);
Products[prod_count].setPrice(price);
for(String dataSt : data)
{
if(dataSt.toLowerCase().contains("imported"))
{
Products[prod_count].setImported(true);
}
else{
Products[prod_count].setImported(false);
}
}
calc.calculateTax(Products[prod_count]);
calc.calculateItemTotal(Products[prod_count]);
prod_count++;
This is the output :
imported box of chocolates
1.50
11.50
imported bottle of perfume
7.12
54.62
This print works System.out.println(Products[1].getProductTotal());
This becomes a null pointer System.out.println(Products[2].getProductTotal());
This also becomes a null pointer System.out.println(Products[0].getProductTotal());
You're skipping lines containing "input".
if(data[i].contains("input")) {
continue; // Products[i] will be null
}
Probably it would be better to make products an ArrayList, and add only the meaningful rows to it.
products should also start with lowercase to follow Java conventions. Types start with uppercase, parameters & variables start with lowercase. Not all Java coding conventions are perfect -- but this one's very useful.
The code is otherwise structured fine, but arrays are not a very flexible type to build from program logic (since the length has to be pre-determined, skipping requires you to keep track of the index, and it can't track the size as you build it).
Generally you should build List (ArrayList). Map (HashMap, LinkedHashMap, TreeMap) and Set (HashSet) can be useful too.
Second bug: as Bohemian says: in data[] you've confused the concepts of a list of all lines, and data[] being the tokens parsed/ split from a single line.
"data" is generally a meaningless term. Use meaningful terms/names & your programs are far less likely to have bugs in them.
You should probably just use tokens for the line tokens, not declare it outside/ before it is needed, and not try to index it by line -- because, quite simply, there should be absolutely no need to.
for(int i = 0; i < numberOfLines; i++) {
// we shouldn't need data[] for all lines, and we weren't using it as such.
String line = reader.readLine();
String[] tokens = line.split("(?<=\\d)\\s+|\\s+at\\s+");
//
if (tokens[0].equals("input")) { // unclear which you actually mean.
/* if (line.contains("input")) { */
continue;
}
When you offer sample input for a question, edit it into the body of the question so it's readable. Putting it in the comments, where it can't be read properly, is just wasting the time of people who are trying to help you.
Bug alert: You are overwriting data:
String [] data = new String[numberOfLines];
then in the loop:
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
So who knows how large it is - depends on the success of the split - but your code relies on it being numberOfLines long.
You need to use different indexes for the line number and the new product objects. If you have 20 lines but 5 of them are "input" then you only have 15 new product objects.
For example:
int prod_count = 0;
for (int i = 0; i < numberOfLines; i++)
{
data = reader.readLine().split("(?<=\\d)\\s+|\\s+at\\s+");
if (data[i].contains("input"))
{
continue;
}
Products[prod_count] = new Product();
Products[prod_count].setName(data[1]);
// etc.
prod_count++; // last thing to do
}

Optimizing Java Code Snippet

I;m trying to shorten code on a program I'm coding and the code I need advice on shortening is this part:
imgRunM[0] = toolkit.createImage(imageURL11);
imgRunM[1] = toolkit.createImage(imageURL12);
imgRunM[2] = toolkit.createImage(imageURL13);
imgRunM[3] = toolkit.createImage(imageURL14);
imgRunM[4] = toolkit.createImage(imageURL15);
imgRunM[5] = toolkit.createImage(imageURL16);
I was thinking it could be written as a loop, just not sure how to write it correctly.
I tried this:
for (int x=1; x<7;x++)
imgRunM[x-1] = toolkit.createImage(imageURL1+x);
It did not error out but when I ran the program, the image did not appear so I'm not really sure what happened.
If anyone has any suggestions I would appreciate it.
I'd suggest making an array of imageURL's also, instead of having a new variable name for each one. Then you could do this:
for (int i = 0; i <= 5; i++) {
imgRunM[i] = toolkit.createImage(imageURL[i+11]);
}
Not sure why you have the +11 offset, but I kept it intact.

Finding string from the next line of an ArrayList

I have this code, it should find a pre known method's name in the chosen file:
String[] sorok = new String[listaZ.size()];
String[] sorokPlusz1 = new String[listaIdeig.size()];
boolean keresesiFeltetel1;
boolean keresesiFeltetel3;
boolean keresesiFeltetel4;
int ind=0;
for (int i = 0; i < listaZ.size(); i++) {
for (int id = 0; id < listaIdeig.size(); id++) {
sorok = listaZ.get(i);
sorokPlusz1 = listaIdeig.get(id);
for (int j = 0; j < sorok.length; j++) {
for (int jj = 1; jj < sorok.length; jj++) {
keresesiFeltetel3 = (sorok[j].equals(oldName)) && (sorokPlusz1[id].startsWith("("));
keresesiFeltetel4 = sorok[j].startsWith(oldNameV3);
keresesiFeltetel1 = sorok[j].equals(oldName) && sorok[jj].startsWith("(");
if (keresesiFeltetel1 || keresesiFeltetel3 || keresesiFeltetel4) {
Array.set(sorok, j, newName);
listaZarojeles.set(i, sorok);
}
}
System.out.println(ind +". index, element: " +sorok[j]);
}
ind++;
}
}
listaZ is an ArrayList, elements spearated by '(' and ' ', listaIdeig is this list, without the first line (because of the keresesifeltetel3)
oldNameV3 is: oldName+ ()
I'd like to find a method's name if this is looking like this:
methodname
() {...
To do this I need the next line in keresesifeltetel 3, but I can't get it working properly. It's not finding anything or dropping errors.
Right now it writes out the input file's element's about 15 times, then it should; and shows error on keresesifeltetel3, and:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
I think your problem is here: sorokPlusz1[id]. id does not seem to span sorokPlusz1's range. I suspect you want to use jj and that jj should span sorokPlusz1's range instead of sorok's and that sorok[jj].startsWith("(") should be sorokPlusz1[jj].startsWith("(").
But note that I'm largely speculating as I'm not 100% sure what you're trying to do or what listaZ and listaIdeig look like.
You're creating sorok with size = listaZ's size, and then you do this: sorok = listaZ.get(i);. This is clearly not right. Not knowing the exact type of listaZ makes it difficult to tell you what's wrong with it. If it's ArrayList<String[]>, then change
String[] sorok = new String[listaZ.size()]; to String[] sorok = null; or String[] sorok;. If it's ArrayList<String> then you probably want to do something more like sorok[i] = listaZ.get(i);
Now for some general notes about asking questions here: (with some repetition of what was said in the comments) (in the spirit of helping you be successful in getting answers to questions on this site).
Your question is generally unclear. After reading through your question and the code, I still have little idea what you're trying to do and what the input variables (listaZ and listaIdeig) look like.
Using non-English variable names makes it more difficult for any English speaker to help. Even changing sorok to array and keresesiFeltetelX to bX would be better (though still not great). Having long variable names that aren't understandable makes it much more difficult to read.
Comment your code. Enough comments (on almost every line) makes it much easier to understand your code.
Examples. If you have difficulty properly explaining what you want to do (in English), you can always provide a few examples which would assist your explanation a great deal (and doing this is a good idea in general). Note that a good example is both providing the input and the desired output (and the actual output, if applicable).

Problem with converting a string to an integer and passing as an ID to a view

There are 20 buttons in an Activity .
The ids are R.id.ButtonR1C1; R.id.ButtonR1C2 .. and so on ie. Row 1, Col 1..
now earlier I had created 20 buttons.
private Button b1,b2,b3...;
and then
b1=(Button)findViewbyId(R.id.ButtonR1C1);
b2=(Button)findViewbyId(R.id.ButtonR1C2);
.... and so on.
Finally
b1.setOnClickListener(this);
b2.setOnClickListener(this);
... 20
so I thought I'd create a Button Array
Button barray[][]=new Button{4][5];
for(int i=1;i<=4;i++) {
for (int j=1;j<=5;j++) {
String t="R.id.ButtonR"+i+"C"+j;
barray[i-1][j-1]=(Button)findViewbyId(Integer.parseInt(t));
}
}
Gives an error..
Any help??
If you have copied your code directly, your syntax is wrong.
Button barray[][]=new Button{4][5];
should be
Button barray[][]=new Button[4][5];
Note the curly bracket instead of square bracket before the 4.
Your next problem, is that you are trying to get the value of R.id.something, but you only have the string representation of it. So, the only way I know to do this is using reflection.
What you need to do is,
Button barray[][]=new Button{4][5];
for(int i=1;i<=4;i++) {
for (int j=1;j<=5;j++) {
Class rId = R.id.getClass();
// this gets the id from the R.id object.
int id = rId.getField("ButtonR"+i+"C"+j).getInt(R.id);
barray[i-1][j-1]=(Button)findViewbyId(id);
}
}
String t="R.id.ButtonR"+i+"C"+j;
Integer.parseInt(t);
This part of your code will definitly throw a runtime exception, because t does not contain a numeric value.
I don't know the format/value of your ID values, but this might work:
Button barray[][]=new Button[4][5]; // type corrected
for(int i=1; i<4; i++) { // changed the for loop...
for (int j=1; j<5; j++) { // changed the for loop...
String t="R.id.ButtonR"+i+"C"+j;
barray[i-1][j-1]=(Button)findViewbyId(t); // t *is* the id (?)
}
}
The Problem is here:
String t="R.id.ButtonR"+i+"C"+j;
barray[i-1][j-1]=(Button)findViewbyId(Integer.parseInt(t));
You're trying to convert a String t to an Integer (while the String is not numeric at all).
This will result in NumberFormatException. You should make sure that t is absolutely numeric.
I used this code:
Class c = Class.forName("com.test.R$id");
Integer i = new Integer(c.getField("ToolsbuttonR3C4").getInt(new R.id()));
System.out.println("HEXA="+i.toHexString(i));
and the ids are in sequential order. so it can be done.
Thanks ppl
So you are trying to convert the String "R.id.ButtonR1C1" to a NUMBER...
That will most certainly give you a NumberFormatException since it is CLEARLY NOT A NUMBER! :)

Categories

Resources