I wrote the following code in JAVA.
package threed;
import java.util.Scanner;
public class Threed_Array {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int b1,b2,b3;
System.out.print("Enter the number of elements in 1st bracket->");
Scanner sc=new Scanner(System.in);
b1=sc.nextInt();
System.out.print("Enter the number of elements in 2nd bracket->");
b2=sc.nextInt();
System.out.print("Enter the number of elements in 3rd bracket->");
b3=sc.nextInt();
int threedarray[][][]=new int[b1][b2][b3];
for(int i=1; i<=b1; i++)
{
for(int j=1; i<=b2; j++)
{
for(int k=1; i<=b3; k++)
{
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
for(int i=1; i<=b1; i++)
{
for(int j=1; i<=b2; j++)
{
for(int k=1; i<=b3; k++)
{
System.out.print(" "+threedarray[i][j][k]);
}
}
}
}
}
I am getting ArrayIndexOutOfBoundsException for this code. This is showing in the line:
threedarray[i][j][k]=sc.nextInt();
Can anybody help me out where the error is occurring? Thank you.
You should always start at index 0, it is the index of the first element of your array:
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
for(int k=0; k<b3; k++) {
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
for(int k=0; k<b3; k++)
{
System.out.print(" "+threedarray[i][j][k]);
}
}
}
furthermore make the check with < not <=
With the last loop you access the array element n+1 where n is the size of that array. Thats the reason for the exception.
I'd say the conditions in your loops are not correct :
for(int i=1; i<=b1; i++)
{
for(int j=1; i<=b2; j++)
{
for(int k=1; i<=b3; k++)
{
it should be :
for(int i=1; i<=b1; i++)
{
for(int j=1; j<=b2; j++)
{
for(int k=1; k<=b3; k++)
{
Also, you should start at 0 in each of them.
I think you want j and k in the 2 inside for loops instead of i. Also, arrays in Java start in index 0, so it should look like this:
for(int i=0; i<b1; i++)
{
for(int j=0; j<b2; j++)
{
for(int k=0; k<b3; k++)
{
...
}
}
}
Arrays in Java are zero-based, try to iterate from 0 to b1-1:
for(int i=0; i<b1; i++)
{
for(int j=0; i<b2; j++)
{
for(int k=0; i<b3; k++)
{
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
[b1][b2][b3]
You create an array using the inputs b1,b2,b3
The array created has length of bx but subscripts from 0 to bx-1. Hence you must loop from 0 to bx-1
Indices start at 0, not 1. Start your three for loops at 0 and iterate to one less than the number provide:
for(int i = 0; i < b1; i++)
{
for(int j = 0; i < b2; j++)
{
for(int k = 0; i < b3; k++)
{
System.out.print(" "+threedarray[i][j][k]);
}
}
}
Apart from the array index problem (see Stefan Beike's answer), you could you an ArrayList.
This would avoid having to ask the user for the number of elements you want to have in your matrix.
Still if you want to keep primitive arrays, you could use System.arrayCopy to reallocate to a greater size array.
The problem here is that you are starting the loop from 1 till the b1,b2,b3 respectively. Array indexes start from 0 not from 1 and ends at the size of the array - 1. So to fix your code you need to modify the code to be the following:
for(int i = 0; i < b1; i++) {
for(int j = 0; j < b2; j++) {
for(int k = 0; k < b3; k++) {
System.out.print("Enter element->");
threedarray[i][j][k]=sc.nextInt();
}
}
}
More generally if you don't know the length/size of the array you are looping on, you can make the loop more generally to be less than the array length. So it would be i < threedarray.length and j < threedarray[i].length and k < threedarray[i][j].length.
The key idea is that the array indexing starts from 0 and ends at its size/length - 1, so to get the last element you access array[array.length-1] and to access the first element you access array[0]
Hope this answers your question.
Related
I have to print the following numbers using nested loops, and I kinda have an idea how, but not how to execute it.
000111222333444555666777888999
000111222333444555666777888999
000111222333444555666777888999
My code so far is something like:
public class opgave_2 {
public static void main(String[] args) {
final int first = 3;
final int second = 3;
final int third = 9;
for (int i = 0; i <= first ; i++) {
for (int j = i; j <= second; j++) {
for (int k = j; k <= third; k++) {
System.out.print(i);
}
}
}
}
}
You should proceed by steps to resolve such problem.
First, you want to print a number 3 times :
int myNumber = 0;
for(int i=0; i<3; i++) {
System.out.print(myNumber);
}
Second, you want to repeat it 9 times and your number to vary from 0 to 9 (seems like an index of loop) :
for(int myNumber=0; myNumber<=9; myNumber++) {
for(int i=0; i<3; i++) {
System.out.print(myNumber);
}
}
Third, you want to display this line 3 times :
for(intj=0; j<3; j++) {
for(int myNumber=0; myNumber<=9; myNumber++) {
for(int i=0; i<3; i++) {
System.out.print(myNumber);
}
}
System.out.println(""); //new line
}
What about something like this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j <= 9; j++) {
System.out.printf("%1$s%1$s%1$s", j);
}
System.out.println();
}
Which uses 2 nested loops. The first to print the line 3 times, and the second to print the numbers per line
you can use a loop, that loops 3 times. in that you put a loop that prints every number from 0 to 9 3 times in a row within the same line
for(int a = 0; a < 3; a++){
for(int i = 0; i < 10; i++){
System.out.print(i+""+i+""+i);
}
System.out.println(); //for the new line
}
or
for(int a = 0; a < 3; a++){
for(int i = 0; i < 10; i++){
System.out.print(i);
System.out.print(i);
System.out.print(i);
}
System.out.println(); //for the new line
}
this should do
I'm coding a Sudoku solver and my teacher recommended that I use a 3d array and since I've never used 3d arrays; I'm having trouble figuring out how to create a loop to iterate through the rows and one through the columns. How would you go about doing this?
Edit: I figured out how to iterate through every third column/row and hopefully I should be able to do the other six eventually, but am I heading in the right direction?
int[][][] = board[9][3][3];
public boolean columnCheck(int[][][] board)
{
boolean filled = false;
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[0].length; j++)
{
System.out.println(board[i][j][0]);
}
}
return true;
}
public boolean rowCheck(int[][][] board)
{
boolean filled = false;
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[0].length; j++)
{
System.out.println(board[i][0][j]);
}
}
return true;
You can use 3 for loops to iterate through a 3D array, e.g.:
public static void main(String[] args) throws FileNotFoundException {
int[][][] array = new int[9][3][3];
for(int i=0 ; i<array.length ; i++){
for(int j=0 ; j<array[i].length ; j++){
for(int k=0 ; k<array[i][j].length ; k++){
System.out.println("[" + i + "][" + j + "][" + k + "]:" + array[i][j][k]);
}
}
}
}
However, for sudoku game, you don't need a 3D array. 2D array would suffice.
public class Main {
public static void main(String[] args) {
int[][][] board = new int[3][3][9];
// Assume that first parameter is row
// The second is column
// Iterating through first row (board[0])
for (int i = 0; i < 3; i++) {
// i is col number
for (int j = 0; j < 9; j++) {
//j is block number
System.out.println(board[0][i][j]);
}
}
// Iterating through second column
for (int i = 0; i < 3; i++) {
// i is row number
for (int j = 0; j < 9; j++) {
// j is block number
System.out.println(board[i][1][j]);
}
}
}
}
I suppose that your 3d array represents the sudoku as follows:
The '9' stands for the 9 small 3x3 blocks. The first '3' for each row of the block and the second '3' for the columns of each block.
That would give the following:
array[0][x][y] | array[1][x][y] | array[2][x][y]
----------------------------------------------------
array[3][x][y] | array[4][x][y] | array[5][x][y]
----------------------------------------------------
array[6][x][y] | array[7][x][y] | array[8][x][y]
To iterate over each row you can do the following:
// The first three rows
// You can probably figure out yourself how to do the last 6,
// and how to combine those 3 seperate sections
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
for (int k=0; j<3; k++) {
System.out.println(array[j][i][k]);
}
}
}
// The first three columns
for (int i=0; i<3; i++) {
for (int j=0; j<7; j+=3) {
for (int k=0; k<3; k++) {
System.out.println(array[j][k][i]);
}
}
}
I hope this will get you going, without solving it all for you.
I'm new to java and just wrote a program for learning purpose.
I have two arrays of strings and i want to compare the length of both string arrays.If lengths are equal then compare the values of each first string array with the values of each second array .If value got matched then print that value.
Not able to rectify where the problem is ?
package com.equal.arrat;
import java.util.ArrayList;
import java.util.List;
public class ArrayEqual {
public static void main(String[] args) {
String s[] = {"anuj","kr","chaurasia"};
String s1[] = {"anuj","kr","chaurasia"};
if (s.length==s1.length)
{
System.out.println(s.length);
for (int i =0 ; i>=s.length;i++)
{
for (int j =0 ;j>=s1.length;j++)
{
System.out.println("test");
if (s[i].equals(s1[j]))
{
System.out.println("ok" + s[i]);
}
else{
System.out.println("not ok");
}
}
}
}
else{
System.out.println("Length Not Equal");
}
}
}
Incorrect logic used. What you meant was < instead of >=
for (int i =0 ; i>=s.length;i++)
should be
for (int i =0 ; i<s.length;i++)
Hope this helps. :-)
At first you are saying i and j is 0 then checking in for loop that if it is greater than s.length or not which is false so it's not executing. Try
for (int i =0 ; i<s.length;i++)
{
for (int j =0 ;j<s1.length;j++)
{
You have errors in your for loop condition checks. This line -
for (int i = 0; i >= s.length; i++)
should be changed to this -
for (int i = 0; i < s.length; i++)
Similarly, change this line -
for (int j = 0; j >= s1.length; j++)
to this -
for (int j = 0; j < s1.length; j++)
your comparators are off in the for loops. That may be why its not working
if (s.length==s1.length)
{
System.out.println(s.length);
for (int i =0 ; i<s.length;i++)
{
for (int j =0 ;j<s1.length;j++)
{
System.out.println("test");
if (s[i].equals(s1[j]))
{
System.out.println("ok" + s[i]);
}
else{
System.out.println("not ok");
}
}
for (int i =0 ; i>=s.length;i++)
On first iteration i=0 and s.length=3 and i>=s.length would translate to 0>=3 which is false and hence the loop will not execute. It should be i<=s.length
You want to compare the length of both string arrays.If lengths are equal then compare the values of each first string array with the values of each second array .so you cant use this >= for comparing length.
simply try it
for (int i =0 ; i<s.length;i++)
{
for (int j =0 ;j<s1.length;j++)
{
change for (int i =0 ; i>=s.length;i++) to
for (int i =0 ; i<s.length;i++)
and same for inner loop
because your first condition itself is not getting satisfied
i=0 and you are checking if i>=s.length(means 3 in this case)
so your for loop will not be executed
Your loops are not correct. Try
for (int i=0; i<s.length; i++)
{
for (int j=0; j<s1.length; j++)
{
I create method to display element in the 2D array. but I can't specify the array length for each dimension. this is my code
public static void display2DArray(String[][] array){
for (int i = 1; i < array.length; i++) {
for (int j = 1; j < array.length; j++) {
System.out.println("Document "+i+ " Section "+j);
System.out.println(" "+array[i][j]);
}
System.out.println(" ");
}
}
Please help me.
Try this way
public static void display2DArray(String[][] array){
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.println("Document "+i+ " Section "+j);
System.out.println(" "+array[i][j]);
}
System.out.println(" ");
}
}
In Java, every intrinsic array object (i.e. Object[]) has the "length" property.
If you have an object of type Object[][], you can view it as (Object[])[], meaning an array of arrays.
So what you do is use index "i" to get an inner array and then an index "j" to get an element from the inner array. Namely:
Object[][] myArray;
for (int i = 0; i < myArray.length; ++i)
for (int j = 0; j < myArray[i].length; ++j)
{ /* do something with myArray[i][j] */ }
First of all, i and j should both default to 0. Second, change j to be array[0].length, and before have a check if array is empty, just return right away. An array can be represented as follows:
{{[0][0] [0][1] [0][2]},
{[1][0] [1][1] [1][2]},
{[2][0] [2][1] [2][2]}}
So to get the height, you just do array.length, but for width, you gotta get one of the interal arrays' lengths, so array[0].length will do
I would like to loop over half of an array in Java; this is because the matrix will be completely symmetric. If I loop throw i columns and j rows, every time I do an operation of matrix[i][j] I will do the exact same operation to matrix[j][i]. I should be able to save time by not looping over half of the matrix. Any ideas on the easiest way to do this?
If you're trying to get a triangle:
for(int i=0; i<array.length; i++){
for(int j=0; j<=i; j++){
..do stuff...
}
}
for (i = 0;i < size; ++i) {
for (j = 0; j < i; ++j) {
result = do_operation(i,j);
matrix[i][j] = result;
matrix[j][i] = result ;
}
}
So you invoke the operation method do_operation only once for each pair.
for(int i = 0; i<array.length; i++){
for(int j = 0; j < array[i].length - i; j++){
// operation here
}
}
Maybe I'm missing something here, but let's say you have two arrays representing your rows and columns respectively, and assuming that it's symmetric (as you say):
int dimension = rows.Length;
for(int i=0; i<dimension; i++)
{
int j = (dimension-1) - i; //need dimension-1 to avoid an off-by-one error
DoSomething(matrix[i][j]);
DoSomehting(matrix[j][i]);
}
This solution has the runtime complexity benefit of only iterating over one loop as opposed to two.