Java program with 2D array -
am writing program decides if number x in matrix of input n x n matrix of number stored in memory in 2d array , each individual rows increasing left right; column top bottom. enter size of matrix n, content, , number x search; display result of search in screen. while testing program input sorted in 2d array.
here code, , showing below compiling error
import java.util.*; public class matrix { public static void main (string[] args){ int search(int mat[4][4]; int n; int x) { int = 0, j = n-1; //set indexes top right element while ( < n && j >= 0 ) { if ( mat[i][j] == x ) { printf("\n found @ %d, %d", i, j); return 1; } if ( mat[i][j] > x ) j--; else // if mat[i][j] < x i++; } printf("\n element not found"); return 0; // if ( i==n || j== -1 ) } // driver program test above function int main() { int mat[4][4] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}, }; search(mat, 4, 29); return 0; } } }
stack trace:
exception in thread "main" java.lang.error: unresolved compilation problems: syntax error on token "(", ; expected syntax error on token "4", delete token syntax error on token "4", delete token syntax error on token ")", ; expected method printf(string, int, int) undefined type matrix void methods cannot return value method printf(string) undefined type matrix void methods cannot return value syntax error on token "int", new expected main cannot resolved type syntax error, insert ";" complete fielddeclaration syntax error, insert "}" complete classbody syntax error on token "}", delete token @ matrix.main(matrix.java:8)
you have search
method inside main()
, should outside. also, declaring main
inside main()
method. remember main method entry point program, , there should exist one:
public static void main(string[] args) { ... }
in java, not supposed declare length of arrays in parameters declaration. also, use commas separate parameters:
public static int search(int[][] mat, int n, int x)
you should use system.out.printf()
instead of printf()
.
finally, array can declared/initialized in multiple ways:
int mat[][] = {{1,2}, {3,4}}; int mat[][] = new int[3][3]; int mat[][] = new int[3][];
the final code should like:
public static int search(int[][] mat, int n, int x) { int = 0, j = n - 1; //set indexes top right element while (i < n && j >= 0) { if (mat[i][j] == x) { system.out.printf("\n found @ %d, %d", i, j); return 1; } if (mat[i][j] > x) { j--; } else { i++; } } system.out.printf("\n element not found"); return 0; // if ( i==n || j== -1 ) } public static void main(string[] args) { int mat[][] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 }, }; search(mat, 4, 29); }
Comments
Post a Comment