Java Array

November 13, 2009 · Print This Article

JAVA:
  1. import java.util.Arrays;
  2.  
  3. public class MainProg {
  4.  
  5. /**
  6. * @param args
  7. */
  8. public static void main(String[] args) {
  9. // TODO Auto-generated method stub
  10. int num1[] = {1,2,3,4};
  11. int num2[] = new int[4];
  12. int num3[] = new int[4];
  13.  
  14. // to populate
  15. for (int i=0 ; i <4 ; i++) {
  16. num2[i] = i;
  17. }
  18.  
  19. Arrays.fill(num3,0);
  20.  
  21. // to display
  22. for ( int value : num2) {
  23. System.out.println(value);
  24. }
  25.  
  26. int value;
  27. for (int x=0 ; x <4 ; x++) {
  28. value = num2[x];
  29. System.out.println(value);
  30. }
  31.  
  32. }
  33. }

JAVA:
  1. import java.util.Arrays;
  2. import java.util.Random;
  3.  
  4.  
  5. public class ArrayEx2 {
  6.  
  7. /**
  8. * @param args
  9. */
  10. public static void main(String[] args) {
  11. // TODO Auto-generated method stub
  12. int e_matrix[][] = new int[3][3] ;
  13. int w_matrix[][] = new int[4][];
  14. int n_items;
  15.  
  16. Random num = new Random();
  17.  
  18. for (int i=0 ; i <e_matrix.length; i++) {
  19. Arrays.fill(e_matrix[i], i+1);
  20. }
  21. display(e_matrix);
  22.  
  23. for (int i=0 ; i <w_matrix.length; i++) {
  24. n_items = num.nextInt(4) + 1 ;
  25. System.out.println("index : " + i + ", length : " + n_items);
  26. w_matrix[i] = new int[n_items];
  27.  
  28. for (int x=0 ; x <w_matrix[i].length ; x++) {
  29. w_matrix[i][x] = num.nextInt(50);
  30. }
  31. }
  32. display(w_matrix);
  33. }
  34.  
  35. public static void display(int the_matrix[][]){
  36. for (int y=0 ; y <the_matrix.length ; y++) {
  37. System.out.println("[row : " + y + "] ");
  38. for (int x=0 ; x <the_matrix[y].length ; x++) {
  39. System.out.print(the_matrix[y][x] + " ");
  40. }
  41. System.out.println();
  42. }
  43.  
  44. }
  45.  
  46. }

Random Posts

Comments

Got something to say?