-
-
Save startupjing/06c91feafb652793cfe8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
read me |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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