Advertisement
AL4ST4I2

Millozzi3

May 26th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. package esercizio3.iterable;
  2.  
  3. import java.util.Iterator;
  4. import java.util.NoSuchElementException;
  5.  
  6. /**
  7.  * Created by stefano on 12/01/16.
  8.  */
  9. public class IterableMatrix implements Iterable<Integer> {
  10.     public final int[][] mat;
  11.  
  12.     public IterableMatrix(int[][] m) {
  13.         if (m.length > 0) {
  14.             this.mat = new int[m.length][m[0].length];
  15.         } else this.mat = new int[0][0];
  16.         for (int i = 0; i < mat.length; i++) {
  17.             for (int j = 0; j < mat[0].length; j++) {
  18.                 mat[i][j] = m[i][j];
  19.             }
  20.         }
  21.     }
  22.  
  23.     public IterableMatrix(int r, int c) {
  24.         mat = new int[r][c];
  25.     }
  26.  
  27.     public static void main(String[] args) {
  28.         int[][] m = new int[][]{
  29.                 {},
  30.         };
  31.         IterableMatrix im = new IterableMatrix(m);
  32.         for (Integer v : im) {
  33.             System.out.println(v);
  34.         }
  35.     }
  36.  
  37.     @Override
  38.     public Iterator<Integer> iterator() {
  39.         return new MYit();
  40.  
  41.     }
  42.  
  43.     private int getRowCount() {
  44.         return mat.length;
  45.     }
  46.  
  47.     private int getColumnCount() {
  48.         if (mat.length > 0)
  49.             return mat[0].length;
  50.         else return 0;
  51.     }
  52.  
  53.     private class MYit implements Iterator<Integer> {
  54.         int r, c;
  55.  
  56.         public MYit() {
  57.             r = 0;
  58.             c = 0;
  59.         }
  60.  
  61.         @Override
  62.         public boolean hasNext() {
  63.             return r < getRowCount() && c < getColumnCount();
  64.         }
  65.  
  66.         @Override
  67.         public Integer next() {
  68.             if (!hasNext())
  69.                 throw new NoSuchElementException();
  70.             final int vale = mat[r][c];
  71.             c++;
  72.             if (c >= getColumnCount()) {
  73.                 c = 0;
  74.                 r++;
  75.             }
  76.             return vale;
  77.         }
  78.  
  79.         @Override
  80.         public void remove() {
  81.             throw new UnsupportedOperationException("remove");
  82.         }
  83.     }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement