如何替换矩阵中的元素?

旺旺(Jordan Mong):

我的输入元素是0或1 ...我想用I替换1并用N替换0。

目前,我能够读取和输出元素,以及如何使用I和N进行替换和输出

        System.out.println("Enter the elements of the matrix");
        for (i = 0; i < m; i++)
            for (j = 0; j < n; j++)
                first[i][j] = in.nextInt();

        // Display the elements of the matrix
        System.out.println("Elements of the matrix are");
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++)
                System.out.print(first[i][j] + "\n");

由于我是Java新手,因此不胜感激。谢谢!

Majed Badawi:

由于您要用字符替换数字,因此矩阵数据类型应为char这是一个例子:

int m = 3, n = 3;
char[][] matrix = new char[m][n];
Scanner scan = new Scanner(System.in);
System.out.println("Enter the elements of the matrix");
for (int i = 0; i < m; i++)
     for (int j = 0; j < n; j++)
          matrix[i][j] = scan.next().charAt(0);
for(int i = 0; i < matrix.length; i++)
    for(int j = 0; j < matrix[i].length; j++)
        if(matrix[i][j]=='1') 
            matrix[i][j] = 'I';
        else if(matrix[i][j]=='0')
            matrix[i][j] = 'N';
System.out.println(Arrays.deepToString(matrix));

样本输入/输出:

Enter the elements of the matrix
1
1
1
0
0
0
1
0
1
[[I, I, I], [N, N, N], [I, N, I]]

根据您的要求,可以按以下方式扫描字符,xxx xxx xxx xxx其中x应为0或1,并根据m和n进行书写:

int m = 4, n = 3;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the elements of the matrix");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < m; i++) {
    String inp = scan.nextLine();
    while (inp.length() != n || !inp.matches("[01]+")) {
        System.out.println("Warning: input must be "+n+" characters and only 1 or 0.");
        inp = scan.nextLine();
    }
    sb.append(inp+" ");
}
String str = sb.toString().trim().replaceAll("1", "I");
str = str.replaceAll("0", "N");
System.out.println(str);

样本输入/输出:

Enter the elements of the matrix
112
Warning: input must be 3 characters and only 1 or 0.
111
000
101
010
III NNN INI NIN

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章