Arrays in for loops - java

I have an array called blockHeights, which contains 3 values inside of it, namely 1,2,3. So blockHeights[0] is equal to 1.
I also have a loop:
for (int i = 1; i <= blockHeights.length; i++)
In the first time around the loop, I want to create a variable called totalBlockHeights where it is
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
However, in the next loop I want that variable to change, so that it only adds blockHeights[1] and blockHeights[2] together, ignoring blockHeights[0].
How would I go about doing this?

Try the following (I'm assuming the third iteration should only include blockHeights[2], following the pattern):
for (int i = 1; i <= blockHeights.length; i++) {
int totalBlockHeights;
for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
totalBlockHeights += blockHeights[j];
}
// do whatever
}

Well, if you want the sum of your array, and the sum of the array without first value
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
totalBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));
this way you only loop once

Try following code:
public class Loop {
public static void main(String[] argv) {
int[] blockHeights = new int[] {1, 2, 3};
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++) {
totalBlockHeights = 0;
for(int j = i; j < blockHeights.length; j++) {
totalBlockHeights += blockHeights[j];
}
System.out.println(totalBlockHeights);
}
}
}

int[] blockHeights = new int[] { 1, 2, 3 };
int totalBlockHeights = 0;
int customBlockHeights = 0;
for (int i = 0; i < blockHeights.length; i++) {
totalBlockHeights += blockHeights[i];
if (i == 0) {
continue;
}
customBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println(customBlockHeights);
This will print:
6
5
You dont need two for to achieve that.

you can perform this on two for loop outer loop for (int i = 1; i <= blockHeights.length; i++), and in inner loop (take a variable j) you can do like int totalBlockHeights = totalBlockHeights + blockHeights[j], and for i<j, you can just continue the for loop.
as answered by btrs20

Related

Filling 2D Array in Java and getting ExceptionOutOfBounds

I searched some entries, but could not answer my question correctly myself.
I'm trying to fill a 2-dimensional array with values.
As a test I'm currently doing this by trying to fill the array with the int number 1.
I do not understand my mistake.
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
Use index 0 to length-1 (as array index start with 0)
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
}
just debug it and you can see, that
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
i, and j change values from 0 to 6, it means that it get's out of arrays bounds ( you iterate over 7 lements, instead of 6 ), just remove = sign in loop bodies
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
Your board array is of size 6x6 hence the board.length is 6.
When you run the loop for (int j = 0; j<=board.length; ij+) it will run from 0 up to 6 but the array indexing is from 0 to 5. So when j=6, ExceptionOutOfBounds occurs since it will be referring to index board[0][6].
Change the condition in both the loops from <=board.length to <board.length

How to understand Loops and Array in java

I am quite confused in array loops that do have nested ones to print the Two Dimensional array. /it contains a loop without curly braces and second one has just opposite way of representing the braces for loops ...
Since i am learning I have just typed the code and got output.
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twod[i][j] + " ");
System.out.println();
}
}
}
The result it generates is
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Try this :
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
}
To properly use the braces always think about the purpose of the loops you have, when do you want them to finish and when do you want them to continue.
In your case, you'll need nested loops for different tasks so you have to properly delimit each one of those tasks.
Fill the the 2D array:
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
Print the 2D array values:
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
Notice that, either for filling or printing the array, your first loop (iterator i) is responsible for the line. It'll stop at I = 3, line number 3. So you'll be in line 0 until you finish the values of all the columns on that line ( [0][0],[0][1],[0][2],[0][4] ) and you just want to go to the second line when your first line is totally filled or printed, and so on. On the print case, you'll need to change the line before the 'i' increments (new line number) and after you have all `'j' values.
To summarize, you'll just want to increment the line ('i') or go to the next line (println()), when your columns ('j') are finished.

Create a 2d array from an ArrayList<Integer>

I have an ArrayList and I want to create a method that will turn it into a 2d array, int[][].
This new 2d array will represent a matrix and it has to be square, so for example if I use [8, 2, 3, 0] the ressult will be {8,2}
{3,0}
public static int[][] convertIntegers(ArrayList<Integer> integers){
int m = (int) Math.sqrt(integers.size());
int[][] ret = new int[m][m];
int cont = 0;
for(int i=0; i<m+1 ; i++)
{
for(int j=0; j<m; j++)
{
cont = cont + 1;
ret[i][j] = integers.get(cont);
;
}
}
return ret;}
Your implementation is almost ok, except for some off-by-one errors:
You need to increment cont after the integers.get call, not before. If you increment before, then the first element of the list will be skipped. An easy way to fix that is to move the incrementing inside the inner loop, counting it together with j.
The outer loop should go until i < m instead of i < m + 1
With the errors fixed:
for (int i = 0, cont = 0; i < m; i++) {
for (int j = 0; j < m; j++, cont++) {
ret[i][j] = integers.get(cont);
}
}
Btw, another way is without using cont at all,
calculating the correct position using i, j and m:
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = integers.get(i * m + j);
}
}

I cant figure out this array

Im doing some personal work, and I am using this array that I thought of, but I cant figure out whats the array is after the code stops running.
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
cnt++;
}
}
I am pretty sure that it ends at [2][1] but I am not 100% sure of it
Just tried this code:
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
cnt++;
System.out.print(numarray[j][i]+" ");
}
System.out.println("");
}
and got this result:
0 1
2 3
4 5
The 'cnt' is incremented by 1 for each iteration. That's why you have 0,1,2,3,4,5.
Also learn how to use debugger in an IDE, you can then explore the value of i, j, cnt by yourself.
why don't you try this?
int cnt = 0;
int[][] numarray = new int[2][3];
for(int i = 0; i < 3; i++) {
for(int j = 0; j< 2; j++) {
numarray[j][i] = cnt;
System.out.println(String.format("array[%d[%d]=%d",j,i,numarray[j][i]));
cnt++;
}
}
you can iterate the array after code finish
for(int i = 0; i < 2; i++) {
for(int j = 0; j< 3; j++) {
System.out.print(numarray[i][j]+" ");
}
System.out.println();
}
summary: cnt is incremented by 1 for each iteration in the inner for loop.
cnt is being incremented by 1 i.e. cnt++ is same as cnt = cnt + 1;
so count values increment from 0 i.e. 0,1,2,3,4,5... Also note, the value of cnt is assigned to the array being created, where you have numarray[j][i] = cnt;
You can simply printout the value using System.out.println(cnt);

ArrayIndexOutOfBoundsException Java Issue

So I have been working on this problem for a while now. I keep getting an ArrayIndexOutOfBoundsException but I am unable to locate where the issue lies. If someone could point me in the right direction, I would really appreciate it! Thanks!
public class Answer {
public static void main(String[] args){
double[] y = {23, 11.1, 50.4};
double[] x = {22.2, 46, 100.0};
Answer answer = new Answer();
answer.answer(y, x);
}
public static int answer(double[] y, double[] x) {
int result = 0;
double percent_1, percent_2;
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
// Calculate percent of first 2 x value array items with y
// all y values. Store the results in a seperate list.
for(int i = 0; i < x.length; i++){
percent_1 = compare(y[i], x[0]);
percent_2 = compare(y[i], x[1]);
compareList_1[i] = percent_1;
compareList_2[i] = percent_2;
}
// Compare those lists to find common number
// There you have your answer.
result = (int)compareLists(compareList_1, compareList_2);
return result;
}
// Calculates percentage from x and y values
public static double compare(double y, double x){
double result = 1 - (y/x);
return result;
}
// Finds common value in lists
public static double compareLists(double[] list_1, double[] list_2){
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
if(list_1[i] == list_2[j]){
return list_1[i];
}
}
}
// Just cus this shouldn't ever return.
return 100;
}
}
In your iteration (compareLists), you should use 'length' (not length + 1)
for(int i = 0; i < list_1.length; i++)
for(int j = 0; j < list_2.length; i++)
I think the problerm is in
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
i < list_1.length + 1 or j < list_2.length + 1 change it to
for(int i = 0; i < list_1.length; i++){
for(int j = 0; j < list_2.length ; j++){
remove +1 from each condition.For j < list_2.length + 1 the list_2.length will give you length of array ie lastIndex +1 and you are adding another +1 in it causing loop condition to be j<lastIndex +1 giving you index error on the last iteration of loop in the line if(list_1[i] == list_2[j]){ for list_2[j]
Also in answer method you declare array by
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
and in the loop you are iterating upto x.length if x.length is greater than y.length the you can get the Index error in compareList_2[i] = percent_2;(inside the loop) because its length is y.length.

Categories