You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java矩阵乘法格式化问题求助:数值格式与输出排版修正

Hey there! Let's work through those two bugs in your matrix multiplication code together:

Issue 1: Displaying .00 double values as integers

The main problem here is that you’re trying to handle formatting during the multiplication calculation, which isn’t ideal—you risk losing precision mid-calculation, and it doesn’t actually control how the final values are printed. Instead, we should handle formatting when we output the matrix, not when we compute it.

Here’s a straightforward way to fix this:

  • Check if each matrix value is a whole number (i.e., if the double equals its integer cast). If yes, print it as an integer; if not, print it with its decimal values.
  • Alternatively, use a DecimalFormat pattern that automatically omits trailing zeros and the decimal point when unnecessary.

Issue 2: Aligning the first matrix row with the title

Your current code adds extra newlines before the title and first row, which pushes them onto separate lines. To fix this, we’ll print the title immediately followed by the first row’s elements when i == 0, with no extra line breaks in between.

Corrected Full Code

import java.text.DecimalFormat;
import java.util.Scanner;

public class ProblemFour {
    public static void main(String[] args) {
        System.out.print("Enter matrix1: ");
        Scanner stdin = new Scanner(System.in);
        String a = stdin.nextLine();
        System.out.print("Enter matrix2: ");
        String b = stdin.nextLine();
        ProblemFour o = new ProblemFour();
        double[][] matrixA = new double[3][3];
        double[][] matrixB = new double[3][3];
        String[] nums1 = a.split(" ");
        String[] nums2 = b.split(" ");
        
        // Formatter to handle clean decimal/integer output
        DecimalFormat formatter = new DecimalFormat("#.##");

        if (nums1.length == nums2.length) {
            matrixA = o.makeMatrix(nums1);
            matrixB = o.makeMatrix(nums2);
            double[][] matrixC = o.multiplyMatrix(matrixA, matrixB);
            
            for (int i = 0; i < 3; i++) {
                if (i == 0) {
                    // Print title + first row on the same line
                    System.out.print("Multiplication of the matrices is: ");
                } else {
                    // Add newline before subsequent rows for readability
                    System.out.println();
                }
                
                // Print each element with proper formatting
                for (int j = 0; j < 3; j++) {
                    double val = matrixC[i][j];
                    if (val == (int) val) {
                        System.out.print((int) val + " ");
                    } else {
                        System.out.print(formatter.format(val) + " ");
                    }
                }
            }
            // Final newline for clean output
            System.out.println();
        } else {
            System.out.println("matrix1 column not equal to matrix2 row");
        }
        stdin.close();
    }

    public double[][] makeMatrix(String[] nums) {
        double[][] matrix = new double[3][3];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                int n = matrix[j].length * i + j;
                matrix[i][j] = Double.parseDouble(nums[n]);
            }
        }
        return matrix;
    }

    public static double[][] multiplyMatrix(double[][] a, double[][] b) {
        double totalElem = 0.0;
        double[][] multipliedMatrix = new double[3][3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                totalElem = 0.0; // Reset total for each new element
                for (int k = 0; k < 3; k++) {
                    // Removed mid-calculation formatting to preserve precision
                    totalElem += a[i][k] * b[k][j];
                }
                multipliedMatrix[i][j] = totalElem;
            }
        }
        return multipliedMatrix;
    }
}

Key Changes Explained:

  1. Formatting Fix:

    • Moved all formatting logic to the output loop, where we check if each value is a whole number before printing.
    • Removed DecimalFormat usage from the multiplyMatrix method to avoid losing precision during calculations.
  2. Title Alignment Fix:

    • Stripped out the extra System.out.println(" "); calls that were adding unnecessary line breaks.
    • When i == 0, we print the title directly followed by the first row’s elements. For later rows, we add a newline first to keep the matrix properly structured.

内容的提问来源于stack exchange,提问作者swordlordswamplord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 23:42:27