【问题标题】:How can i replace the elements inside matrix?如何替换矩阵内的元素?
【发布时间】:2020-07-03 21:18:58
【问题描述】:

我的输入元素是 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 新手,任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: java arrays matrix


    【解决方案1】:

    由于您想将数字替换为字符,因此矩阵数据类型应为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
    

    【讨论】:

    • 但实际上我像这样从控制台获取输入 = new Scanner(System.in); m = in.nextInt(); n = in.nextInt();
    • 为什么不将输入读取为字符或字符串呢?
    • @JordanMong 我更新了答案以用字符填充矩阵。
    • 非常感谢!你很有帮助。还有一件事,无论如何我可以读取这样的输入 - m 是 4,n 是 3.. 就像一起排在一起 110 000 110 000
    • 你的意思是用户会输入一次?
    猜你喜欢
    • 1970-01-01
    • 2017-05-09
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多