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++)
{
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.
This is my current code:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
/*for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + "");
}
}*/
}
}
I can't seem to do it. I got confused and I removed the part of testing w/commenting. Just ignore that.
I am aiming to get a two dimensional array like this:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
However, I just don't get it. How can I get that result? I'm a beginner at java.
First, you need to populate the array with data, and you forgot System.out.println for each row of the array.
int [][] twoD = new int [5][5];
// populate array with data
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = (j+1)*(i+1);
}
}
// print result
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j]);
System.out.print(" ");
}
System.out.println();
}
You have to populate the data as well:
int[][] arr = new int [5][5];
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
arr[i][j] = (j+1)*(i+1);
}
}
And the code to print would be:
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
You are doing fine, you just need to put line jump System.out.println(); every time the second for ends
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
You are on the right track, that for loop will print out the array like that, all you need to do is print a new line character after finishing the for(j) loop. But, at least in the snippet you posted, you aren't actually doing any assignments, so there aren't any values in your array to print, Java will initialize all ints to zero for you.
The array doesn't just automatically populate with incrementing integers, rather each cell of the array will automatically initialized to 0, you have to set the values you want the array to contain. You can use the concept of your testing class to do this if you wish, just set each cell of the 2D array to a certain value. After that, you can print out the array, making sure to print a each row of the array on a new line. For instance:
public static void main(String[] args) {
int [][] twoD = new int [5][5];
int increment = 1;
for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
twoD[i][j] = increment++;
}
}
for(i = 0; i<5; i++){
for(j = 0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
The first set of nested for loops will set each of the cells of the 2D array to the incremented integers you want (note increment++ will first set the cell to the value increment currently is, then add one to the variable). The second set of nested for loops will print out the array as you desire.
refer this code
int[][] twoD = new int[5][5];
// add values to array
for (int i = 0; i < 5; i++) {
int val = 1;
val = val + i;
for (int j = 0; j < 5; j++) {
twoD[i][j] = val * (j + 1);;
}
}
// Print array
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
as others pointed out you need to print it nicely to see the pattern, i and j are indices of your array. However, I see that you have a nice pattern so just running two loops won't solve the problem.
Maybe something like this would help (not giving exact answer intentionally)
int [][] twoD = new int [5][5];
int i;
// initialize
int c = 1; int j = 0;
for(c=1; c<5; c++) {
for( i = 1; i<=5; i++){
twoD[i-1][c-1] = c*c*i; twoD[c-1][i-1]=c*c*i;
}
}
for( i = 0; i<5; i++) {
for( j = 0; j<5; j++) {
System.out.print(twoD[i][j]);System.out.print(" " );
}
System.out.println("\n");
}
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.
I'm working on a program that requires me to take in a 1-D String array from a file and turn it into a 2-D array. Taking in the array from the file works fine, but I can't get the second part to work.
The code I'm working with is:
char[][] array2 = new char [7][5];
for (int i = 0; i < array1.length; i++)
{
array2[i]= array[i].toCharArray();
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
{
System.out.println(array2[i][j]);
}
}
The array is supposed to print in a grid format, but is printing downward.
Any help is appreciated, thanks.
Use print instead of println in inner loop and after each loop print a blank line with println.
for (int i = 0; i < 7; i++) // see changes 5/7. You did "new char[7][5]" not [5][7]
{
for (int j = 0; j < 5; j++) // see changes 7/5
{
System.out.print(array2[i][j]);
}
System.out.println();
}
Update:
Following is a program that convert String array to 2D char array.
public class StringToChar {
public static void main(String[] args) {
String[] strArr = { "HELLO", "WORLD" };
char[][] char2D = new char[strArr.length][];
for (int i = 0; i < strArr.length; i++) {
char2D[i] = strArr[i].toCharArray();
}
for (char[] char1D : char2D) {
for (char c : char1D)
System.out.print(c + " ");
System.out.println();
}
}
}
few suggestions,
replace char[][] array2 = new char [7][5]; with char[][] array2 = new char [array1.length][]; (where array1 holds your strings), so your 2d array will have as many rows as you have strings
your loop
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
....
}
change to
for (int i = 0; i < array2.length; i++)
{
for (int j = 0; j < array2[i].length; j++)
....
another thing is if you want your string printed in rows, use System.out.print, and whenever you finished inner loop, print out'\n' character
You are using println, which is why each character is printed on its own line. You must use print instead.
Note that your initialization with
new char [7][5];
doesn't work as you expect because the inner arrays will be overwritten. Use
new char[7][]
for the same result, but more clarity as to your intent. Here
for (int i = 0; i < 5; i++)
for (int j = 0; j < 7; j++)
you have apparently reversed the order of indices: you are iterating only through 5 outer arrays, but you have allocated 7. What you should do instead is check against the actual array length and not a hardcoded number. The inner array may be of any size, after all (it depends on the string length).
Have a look at the String.toCharArray()
If it is printing downwards then change
for (int i = 0; i < 7; i++) //row loop
{
for (int j = 0; j < 5; j++) //column loop
{
System.out.print(array2[i][j]);
}
System.out.println(); //add here
}
Have a look at
formatting
print vs println