Currently working on a student project. I want to figure out the highest number and sort it by bubble sort, the number is parsed from a JLabel, but I get this error everytime. Here is a code snippet:
JLabel[] wuerfelsummen = new JLabel[7];
wuerfelsummen[0] = player1_wuerfelsumme;
wuerfelsummen[1] = player2_wuerfelsumme;
wuerfelsummen[2] = player3_wuerfelsumme;
wuerfelsummen[3] = player4_wuerfelsumme;
wuerfelsummen[4] = player5_wuerfelsumme;
wuerfelsummen[5] = player6_wuerfelsumme;
public int ermittleGewinner(JLabel[] w)
{
int temp;
int[] zahlen = new int[w.length];
for(int i=0; i<=zahlen.length; i++)
{
if(w[i].getText() == null)
{
zahlen[i] = 99999999;
}
else
{
zahlen[i] = Integer.parseInt(w[i].getText());
}
}
for(int i=1; i<zahlen.length; i++)
{
for(int j=0; j<zahlen.length-i; j++)
{
if(zahlen[j]>zahlen[j+1])
{
temp=zahlen[j];
zahlen[j]=zahlen[j+1];
zahlen[j+1]=temp;
}
}
}
for(int i=0; i<=zahlen.length; i++)
This is incorrect, as arrays are 0-indexed, meaning they reach from 0 to length-1.
Change it to
for(int i=0; i<zahlen.length; i++)
Interestingly enough, your other loops avoid this pitfall, although you will still have to be careful about the j+1 later on. Make sure that this can never be >= zahlen.length.
You could simply initialize j with 1 instead of 0 and then replace all occurences of j with j-1 and j+1 with j
change "i<=zahlen.length" in your for loop to "i < zahlen.length".
remember arrays are 0 indexed so you are trying to access an element one index outside of how large your array is with the "<=" method you are currently using
The second loop should start at i=0 instead of i=1. By using i=1, you are again going to try to access one element past the size of your array
ArrayIndexOutOfBounds expcetion comes when code tried to access an element of an array which is not present. In your code, since you are FOR looping one extra time for(int i=0; i<=zahlen.length; i++), you are getting this exception. Keep FOR loop as for(int i=0; i<zahlen.length; i++)
You have not to just check for zahlen[i] but also for w[i] because you are looping on length of zahlen and it may so happen that w is of lesser length then zahlen.
Related
public static void countingSort(Integer[] a, int n) {
//TODO
//COMPLETE THIS METHOD
int[] counter = new int[n+1];
int[] sorted = new int[a.length];
Arrays.fill(counter,0);
// fills counter array with each number count
for ( int i = 0 ; i < a.length; i++){
counter[a[i]] += 1;
} // adds n-1 index + n index
for (int i = 1; i < counter.length; i++) {
counter[i] = (counter[i] + counter[i-1]);
} // shifts array to the right
for (int i = counter.length-1; i > 0; i--) {
counter[i] = counter[i-1];
} // fills sorted array with the sorted out counts
for (int i = 0; i < a.length; i++ ){
sorted[counter[a[i]]] = a[i];
counter[a[i]]++;
}
}
When ran it throws an array out of bound exception in the body of the first for loop. Im having trouble seeing it, if anyone could help guide me, it'd be much appreciated.
When ran it throws an array out of bound exception in the body of the
first for loop.
That would be this:
for ( int i = 0 ; i < a.length; i++){
counter[a[i]] += 1;
}
Im having trouble seeing it, if anyone could help
guide me, it'd be much appreciated.
An ArrayIndexOutOfBoundsException in that loop can only mean that you are exceeding the bounds of a or those of counter. It is clear from inspection that you are not exceeding the bounds of a (though you could both eliminate that possibility and make the code a bit cleaner by switching to an enhanced for loop). The only remaining possibility is that you are exceeding the bounds of counter.
The approach you've implemented supports only non-negative integers in the input array, and requires the method invoker to pass an upper bound on the element values as the second parameter. If those constraints are not satisfied then an exception such as you observe will be thrown.
That is, if the exception is thrown where you say it is, then the problem is with the input.
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
So, I am building a method to check a 2d array for a target value and replace each adjacent element with that target value. I have literally tried to brainstorm the solution to this for about an hour and I just want to know if anyone can help me with this, this is the code I have so far
public int[][] replaceValue(int n, int[][]y){
int [][]temp0 = new int[y.length][y[0].length];
int[]top, down ,left, right = new int[y[0].length];
for(int row = 0; row < y.length; row++){
for(int col = 0; col < y[row].length; col++){
temp0[row][col] = y[row][col];// new array so I wouldn't mess with the array passed in
}
}
for(int row = 0; row < temp0.length; row++){
for(int col = 0; col < temp0[row].length; col++){
top[row] = temp0[row-1][col];
down[row] = temp0[row+1][col];
right[row] = temp0[row][col+1];
left[row] = temp0[row] [col-1];
}
}
I got error messages such as I didn't initialize my top and left and right and down variables but I simply don't understand how the logic works for checking the adjacent elements and making sure the whole array is not replaced with the target value. Thanks
The question is a little confusing so I will try to interpret it.
What you are given is a 2-dimensional array with some integer values. Your function should scan the 2-d array, and if you find some target value,
return a 2-d array with the adjacent indices as the target value as well.
For example, if we have a 3x3 array and the target is 2...
1 1 1 1 2 1
1 2 1 ====> 2 2 2
1 1 1 1 2 1
Your problem is that you can't think of a way to change the value without changing the entire array to 2.
Solution One: You scan for the target value in the given array, but you update the values in the temporary array.
Solution Two: You scan the temporary array, and store whether or not it should be changed using a 2-d boolean array.
Solution One is much better in terms of efficiency (both memory and time), so I'll just give you my solution #2, and leave you to do Solution One on your own.
Also, please use more descriptive variable names when it matters :P (why is the input called temp??)
public static int[][] replaceValue(int target, int[][] currArray){
int[][] temp = new int[currArray.length][];
//get a boolean array of same size
//NOTE: it is initialized as false
boolean[][] needsChange = new boolean[currArray.length][currArray[0].length];
//copy the current array into temp
for(int i = 0; i < currArray.length; i++){
temp[i] = currArray[i].clone();
}
//Go through each value in the 2d array
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++){
//if it is the target value, mark it to be changed
if(temp[i][j] == target){
needsChange[i][j] = true;
}
}
}
//Go through each value in the 2d array
for(int i = 0; i < temp.length; i++){
for(int j = 0; j < temp[0].length; j++){
if(needsChange[i][j]){ //NOTE: same as "needsChange[i][j] = true;"
//Now, we will check to make sure we don't go out of bounds
//Top
if(i > 0){
temp[i-1][j] = target;
}
//Bottom
if(i + 1 < temp.length){
temp[i+1][j] = target;
}
//Left
if(j > 0){
temp[i][j-1] = target;
}
//Right
if(j + 1 < temp[0].length){
temp[i][j+1] = target;
}
}
}
}
//return the new array we made
return temp;
}
You have not initialized your local variables before first use. So you need to change your 3rd line to some thing like the below code:
int[] top = new int[temp[0].length], down = new int[temp[0].length],
left = new int[temp[0].length], right = new int[temp[0].length];
After that your code is compiled and you can check your logic.
What is being done in this for loop, counter and arr are two different ArrayLists.
// 3. store count of each number as we iterate through arr
for(int i = 0; i< arr.size(); i++){
counter[arr.get(i)]++;
}
arr contains indexes that the corresponding elements for them on counter should be incremented.
For example:
arr = [1,3,4]
Then the elements in 1,3 and 4 will be incremented in the array counter.
I highly recommend you to debug your code to better understand the flow of the program. You should also be careful with ArrayIndexOutOfBoundsException:
for(int i = 0; i< arr.size(); i++) {
if(arr.get(i) < 0 || arr.get(i) >= counter.length) {
continue;
}
counter[arr.get(i)]++;
}
Or doing something else, depends on the logic of your program.
If arr contains integer numbers it is index of counter array. Then you are incrementing the value of counter array on arr.get(i) index. I hope you understand what I am saying.
I'm trying to populuate an array with random numbers to be sorted and used in a binary search. All of my code seems to work fine except the generating part. The numbers need be between 1-32767 and I continue to get 0.
for(int i = 0; i < SIZE-1; i++){
array[i] = (gen.nextInt(32767 - 1) + 1);
}
// Print out five entries
for(int i = 0; i < 5; i++){
System.out.println(array[i]);
}
// Sort array
Arrays.sort(array);
// Print out first five sorted entries
for(int i = 0; i < 5; i++){
System.out.println(array[i]);
}
After they're sorted and printed, the first entry is always 0. Perhaps this has to do with the array sorting, and I'm not realizing it. Any suggestions?
You're never setting the last element of the array -- use i < SIZE, not i < SIZE-1.