对二维整数数组进行操作
package lab3;
import java.util.Scanner;
public class Part2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the count of columns: ");
int columns = scanner.nextInt();
System.out.println("Enter the count of rows: ");
int rows = scanner.nextInt();
int[][] matrix = new int[rows][columns];
java.util.Random random = new java.util.Random();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
matrix[i][j] = random.nextInt(10) - 4;
}
int[] countByRows = new int[rows];
//输出二维数组
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
//计数至少有一个零元素的行
int amount = 0 ;
for (int i = 0; i < rows; i++)
if ( [rows] == 0)
{
amount = amount+ 1 ;
}
System.out.println("The number of rows with at least one zero element is" + amount);
//找出具有相同元素最多的列的列数
}
}
计数至少有一个零元素的行报错
1.计数至少有一个零元素的行
2.找出具有相同元素最多的列的列数
package lab3;
import java.util.Scanner;
public class Part2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the count of columns: ");
int columns = scanner.nextInt();
System.out.println("Enter the count of rows: ");
int rows = scanner.nextInt();
int[][] matrix = new int[rows][columns];
java.util.Random random = new java.util.Random();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
matrix[i][j] = random.nextInt(10) - 4;
}
int[] countByRows = new int[rows];
//输出二维数组
//计数至少有一个零元素的行
int amount = 0 ;
for (int i = 0; i < rows; i++)
{
boolean flag=false;
for (int j = 0; j < columns; j++){
if(matrix[i][j]==0){
flag=true;
}
System.out.print(matrix[i][j] + " ");
}
if(flag)
amount = amount+ 1 ;
System.out.println();
}
System.out.println("The number of rows with at least one zero element is" + amount);
//找出具有相同元素最多的列的列数
}
}
题目是什麽?
countByRows 数组没有初始化,也没有给数组赋值啊。应该将初始值都设置为1
你得遍历矩阵每一行,判断元素是0,然后将countByRows数组指定行的值设置为0,然后用下面的循环才能知道有几行有0
for (int i = 0; i < rows; i++)
if (countByRows[i]== 0)
{
amount = amount+ 1 ;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!