Algorithm problems, android java - java

I've a problem but i really don't understand why. The problem is when i want to add an element in my ArrayList.
Here is my code :
ArrayList<Integer> lesCasesCoches = new ArrayList<Integer>();
lesCasesCoches.clear();
Log.w("Test", "je beug pas" + idCasier);
for (int f = 0; f < laCave.requeteIdCasier.size(); f++) {
if (laCave.requeteIdCasier.get(f) == idCasier) {
Log.w("Test", "size" + f);
Log.w("Test", "id casier" + laCave.requeteIdCasier.get(f));
Log.w("Test", "id case" + laCave.requeteIdCase.get(f));
int casesAdd = laCave.requeteIdCase.get(f);
Log.w("Test", "que vaut add" + casesAdd);
lesCasesCoches.add(casesAdd);
Log.w("test", "Cases cochés" + lesCasesCoches.get(f));
}
}
Here is my error log:
test: je beug pas2
test: size2
test: id casier2
test: id case5
test: que vaut add5
==> here the bug message
delvikvm: threadid=1: thread exiting with uncaught exception ( group=0x415072a0)
java.lang.indexOutOfBoundsException: Invalid index 2, size is 1
Sorry for my bad english.
Thank you very much for the time you spend for me

Change
Log.w("test","Cases cochés"+lesCasesCoches.get(f));
to
Log.w("test","Cases cochés"+lesCasesCoches.get(lesCasesCoches.size()-1));

I think this make exception error.
Log.w("test","Cases cochés"+lesCasesCoches.get(f));
change this.
Log.w("test","Cases cochés"+casesAdd);

Few things here:
1) why do you need to clear an Array you just created?
2) you access laCave.requeteIdCase and laCave.requeteIdCasier at the position f but f is only bound to laCave.requeteIdCasier.size(). That probably is crashing because requeteIdCase has lesser elements than requeteIdCasier (whatever those terms mean :) )

It probably happens because of this statement if (laCave.requeteIdCasier.get(f) == idCasier)
because if it's not true then for loop will go forward and increase f hence it won't match with
lesCasesCoches.add(casesAdd);
Log.w("test","Cases cochés"+lesCasesCoches.get(f));
so instead of getting f'th item you should get the last one
Log.w("test","Cases cochés"+lesCasesCoches.get(lesCasesCoches.size()-1));

The error is actually caused by logging:
Log.w("test", "Cases cochés" + lesCasesCoches.get(f));
Explanation:
test: je beug pas2
test: size2
test: id casier2
test: id case5
test: que vaut add5
java.lang.indexOutOfBoundsException: Invalid index 2, size is 1
From the debug log, you add the first Integer 5 from casesAdd into lesCasesCoches when f is 2. Since this is the first time you add the number, the size() of lesCasesCoches is 1. Then, when you call the problematic line, you're trying to access the third (from 0-based index) element of lesCasesCoches, resulting in IndexOutOfBoundsException.
The solution is to either remove the line if it's not really needed, or to use lesCasesCoches.get(lesCasesCoches.size() - 1) to get the last added Integer from lesCasesCoches.

Related

Error array index out of bounds in some code

There is an array index out of bounds exception in my recursive function. Can someone try to point out to me why that is the case?
This line: return minChange(a, IntegerList); is having the array index out of bounds exception as well as most likely this line:
return minimumValue(1 + minChange(a - d, integerList), minChange(a, updatedList));
/* Function minChange: Minimum Change
Pseudo-code:
minChange(0, ds) = 0
minChange(a, []) = Failure
minChange(a, d :: ds) = minChange(a,ds) if d > a
minChange(a, d :: ds) = min(1 ++ minChange(a - d, d :: ds) otherwise
*/
public int minChange(int a, List<Integer> integerList) {
//int minimumResult = 0;
int indexNumber = 0;
int d = integerList.get(indexNumber); (line 246)
if(a == 0) {
// If a is 0 return 0
return 0;
} else if(integerList.isEmpty()) {
return -1;
} else if(d > a) {
integerList.remove(indexNumber); // Remove first element from list
// Recursive call to minChange
return minChange(a, integerList); (line 261)
} else {
// Create updatedList and remove first element
List<Integer> updatedList = integerList;
updatedList.remove(indexNumber);
indexNumber++;
return minimumValue(1 + minChange(a - d, integerList), minChange(a, updatedList)); (line 269)
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out-of-bounds for length 0
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:246)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:261)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:261)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:261)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:261)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:261)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:261)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:261)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:269)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:269)
at AlgorithmsSetZero.minChange(AlgorithmsSetZero.java:269)
How can I fix this array index out of bounds exception. It seems one line needs to be fixed. If so how can I fix this error? What are some ways?
Why it Fails:
A specific sequence of events that leads to the out of bounds exception would be, for example:
minChange(1, [4]) // goes into second-to-last (else if) case, since 4 > 1. 4 is then removed.
minChange(1, []) // crashes
It's not clear what your code was intended to do in this case, since your pseudo-code doesn't define minChange(a, ds).
Even if we stipulate that the input list has to have more than one item, we'll often hit this same case:
minChange(5,[4, 8])
minChange(1,[8])
minChange(1,[])
I'm not sure what you intended to happen here, but, anyway, there are other issues...
Bugs:
There is very likely a bug in your code with this line:
// this just creates another reference to the existing list
// https://stackoverflow.com/questions/6536094/java-arraylist-copy
// meaning: both recursive calls will operate on the same list
// even though one uses the "updatedList" reference and one uses "integerList"
List<Integer> updatedList = integerList;
Also, the use of indexNumber indicates a bug, since it's only ever used when it has value 0 - the incrementing is pointless. Remember that local variables in the function are getting 'reset' in each recursive call, unless you pass them as a parameter.
Debugging Strategies:
First, clarify what you actually want the algorithm to do.
Then, check what it's actually doing. As a debugging technique, I would recommend adding some print statement at the start of the function call:
System.out.println("minChange(" + a + ", " + integerList + ")");
...so that you can see a log of what happened before the crash. You can also use a debugger for this purpose.
Finally, once it works on some simple cases, write a fuzz tester that checks your algorithm on a bunch of random lists and as of different sizes, to see if there are any cases that you missed.

preventing Array index out of bounds exception with coins

I am trying to figure out a way to separate a monetary value into quarters, dimes, nickels and pennies in the most efficient way. This is currently my code:
public class CoinReader {
private static int amount = 0;
public static void main(String[] args) {
amount = (int)(Double.parseDouble(args[0])*100);
System.out.println("Five: " + computeCoin(500));
System.out.println("one: " + computeCoin(100) );
System.out.println("Q : " + computeCoin(25) );
System.out.println("D : " + computeCoin(10) );
System.out.println("N : " + computeCoin(5) );
System.out.println("P : " + computeCoin(1) );
}
public static int computeCoin(int cointValue) {
int val = amount / cointValue;
amount -= val * cointValue;
return val;
}
}
I am currently getting an Array index out of bounds exception and I know it has something to do with the String array and the amount variable but I am trying to learn about arrays and I am trying to get this program to work. Any help would be appreciated. Thanks.
You are using args[0] and args appears to be empty.
How do you call your program ? You must have forgotten to pass a parameter.
args array is empty, there is no element with index 0. You have to pass one command line argument to your program. When running from a command line make sure you pass a numeric value as an argument like this:
java CoinReader 113.25
It runs:
javac CoinReader.java
java CoinReader 1230
Ouput
Five: 246
one: 0
Q : 0
D : 0
N : 0
P : 0
Have fun to make it work correctly :-P
EDIT:
As already mentioned by the other guys the parameter String args[] refers to the arguments you provide on the command line when you run your compiled Program. You'll get an ArrayOutOfBondsException when you provide no argument as the array will be empty then.
When I say Have fun to make it work I mean that there seems to be an error in your computeCoin method as it won't output results for P, N, D and Q. But this is beyond your initial question.
SECOND EDIT:
It not just runs. It runs perfectly fine.
java CoinReader 10.11
Output:
Five: 2
one: 0
Q : 0
D : 1
N : 0
P : 1

Groovy Array.addAll method remove the elements from original array

Ok I'm sure I'm doing something wrong here.
result = []
for (aMp in arMap) {
println("0 " + result)
println("1 " + aMp)
println("2 " + delegate.findSingleMap(aMp))
result.addAll(delegate.findSingleMap(aMp))
println "3 " + result
}
return result
The println result are the following: (I have 2 element in arMap, so it print the four value 2 times)
0 []
1 [ID:XXX, Type:4]
2 [[First:21/Nov/2013, Type:4, error code:SXR07, ID:XXX, Test ID:5]]
3 [[First:21/Nov/2013, Type:4, error code:SXR07, ID:XXX, Test ID:5]]
0 [[First:21/Nov/2013, Type:4, error code:SXR07, ID:XXX, Test ID:5]]
1 [ID:YYY, Type:4]
2 [[First:12/Oct/2012, Type:4, error code:SXR07, ID:YYY, Test ID:6]]
3 [[First:12/Oct/2012, Type:4, error code:SXR07, ID:YYY, Test ID:6]]
As you can see the findSingleMap function work properly, but the second time I use the AddAll, my result array loose the value XXX.
What am I doing wrong?
As stated by the OP int the comments the method findSingleMap modifies the (global) result variable.
for (aEl in map) {
result = result.findAll { it[aEl.key] == aEl.value }
}
return result
Not writing def in front a variable declares it (in simple scripts) global, which might result in strange behaviour like this. So don't do it, unless you have to codegolf.

arraylist.contains(string) not evaluating string

Strangely enough, I have a feeling I'm missing something here with using ArrayList.contains(Object o), but it's not coming to me right at the moment, can someone point me in the right direction?
I have two ArrayList that contain a list of values. I want to compare them and get the count of the matches in the files, so I have done this:
ArrayList<String> policyNumbersBene = new ArrayList<String>();
policyNumbersBene.add("YOOHOO");
ArrayList<String> policyNumberDly = new ArrayList<String>();
policyNumberDly.add("YOOHOO");
int count = 0;
for (String policyNumber : policyNumbersBene) { // compare 2 arraylists to each other.
count += (policyNumberDly.contains(policyNumber) ? count : 0;
}
'SYSO'(count);
I believe I should get 1 in the output of the counter, but I am getting 0 each time. When I slapped a debugger on there, I can see the list of values in the arrays, and I see "YOOHOO" in there. Can someone point out what I am doing wrong? I feel like a complete java newbie asking this.
When you execute this line, count is 0 so you get 0 + 0
count += (policyNumberDly.contains(policyNumber)) ? count : 0;
Fix:
count += (policyNumberDly.contains(policyNumber)) ? 1 : 0;
I would suggest, if you needs to calls the method contains, to use an LinkedHashset instead of an ArrayList.
The call will be in constant time instead of O(n).
System.out.println(policyNumberDly.contains(policyNumber) ? 1 :0);
it prints 1 so state count=1;

Problem with my for loop. I have never used this type before and it's not working like a regular loop

I have a Project class that holds a name and various other attributes. Everytime a new Project is made it is added to an ArrayList.
ArrayList<Project> mProject = new ArrayList<Project>();
I have most of the code in a different question. I don't feel like I should ask it there as it has a different question on it. But if you want to check out more of the code it's here:
Can I use a method from a different class that I have added to an ArrayList?
And here is where I'm stuck. This is the first time I've used this type of loop before and I don't know what's going on. I have seen tutorials just pass over this loop with a "you should know what happens here" attituded. So if you could explain this loop that would be great also.
And on to the code:
System.out.println("Select one of the fallowing projects:");
for (Project proj : mProject){
int i= 1;
i++;
System.out.println( i + ": " + proj.returnName());
}
My output is this:
Select one of the fallowing projects:
2: Greg
2: Mike
It looks like it's not going though the code. So I'd love an explanation or a tutorial with this loop. Thanks.
If I use a regular loop how whould I go about using the methods from the mProject arraylist?
for ( int i = 0; i<= mProject.size() ; i++){
Project proj = mProject;// This won't compile.
if (choice == proj.returnName()){
}
}
If you move the int declaration out of the loop it will increment as you would expect, it is getting reassigned every time:
int i= 1;
for (Project proj : mProject){
i++;
System.out.println( i + ": " + proj.returnName());}
your int Variable gets initalised with 1 in the for each loop, then incremented. In the next iteration, it gets initialised with 1 again, then incremented.
int i= 1;
System.out.println("Select one of the fallowing projects:");
for (Project proj : mProject){
i++;
System.out.println( i + ": " + proj.returnName());
}
This should work properly
Its basically just a different way of writing a for loop, also known as a foreach loop.
http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html
In your code example, the variable proj gets set to the next item in the list mProject. This happens until the list has nothing left to iterate through.
The variable i is local to the for loop, so it is being recreated each time, as others have said. In other words, every iteration of this loop will make i = 2, as you can see from your output.
See that you delcare the "int i = 1; " inside the loop.
So, every time the loop "loops", i gets the value 1 again.
It should be:
int i =1;
for(Project proj: mProject) {
i++;
System.out.println( i + ": " + proj.returnName());
}
See the "int i = 1 ; " out of the loop ?
This type of loop is known as a foreach loop in Java. Basically, it's shorthand for saying, "for each item in this array/collection/iterable, do ..."
The shorthand is nice, but the downside, as you have run into, is that you don't have access to the index or iterator inside the loop when you use this form. So you should either separately track the index (like you're already trying to do, see Terrell's answer for the correct way), or use standard loop syntax, e.g. for(int i=0; i<mProject.length; i++)
for (Project proj : mProject){
System.out.println( proj.returnName() );
}
means
For each Project in the Project Set mProject, which has been defined as:
{ GregProject, MikeProject }
Print out that project's returnName. proj is re-evaluated at each step of the loop, to point to the next Project in the Set.

Categories