Skip to content

Instantly share code, notes, and snippets.

@startupjing
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save startupjing/06c91feafb652793cfe8 to your computer and use it in GitHub Desktop.
Save startupjing/06c91feafb652793cfe8 to your computer and use it in GitHub Desktop.
import java.util.*;
public class FillZero {
/**
* user enters the matrix and program sets zeros
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true){
System.out.println("Please enter # row of your matrix: ");
int row = input.nextInt();
System.out.println("Please enter # column of your matrix: ");
int col = input.nextInt();
int[][] matr = new int[row][col];
System.out.println("Please enter the matrix by rows: ");
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
matr[i][j] = input.nextInt();
}
}
writeZero(matr, row, col);
System.out.println("The new matrix is: ");
printMatrix(matr, row, col);
System.out.println("continue?(y/n): ");
if(input.next().equals("n")){
System.exit(0);
}
}
}
/**
* set zero for rows and columns
* @param matr
* @param row
* @param col
*/
public static void writeZero(int[][] matr, int row, int col){
//lists to store the row/column number where zeros lie
ArrayList<Integer> zeroRow = new ArrayList<Integer>();
ArrayList<Integer> zeroCol = new ArrayList<Integer>();
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
if(matr[i][j] == 0){
zeroRow.add(i);
zeroCol.add(j);
}
}
}
int[] newRow = new int[col];
//set zeros
for(int i: zeroRow){
matr[i] = newRow;
}
for(int j: zeroCol){
for(int k=0; k<row; k++){
matr[k][j] = 0;
}
}
}
/**
* print the matrix
* @param matr
* @param row
* @param col
*/
public static void printMatrix(int[][] matr, int row, int col){
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
System.out.printf("%-5d", matr[i][j]);
}
System.out.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment