I’m trying to write a program which prompts the user to enter two 3×3 matrices and displays their product.
For example, a user can enter:
Matrix A: 2 4 6 8 10 12 14 16 18 Matrix B: 1 2 3 4 5.6 6.6 7.4 8.1 9
Below is what I have tried, but I keep getting this error. Any help to point me in the right direction would be appreciated. I’m trying to get it to one decimal place:
Exception in thread "main" java.util.IllegalFormatPrecisionException: 2
at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2892)
at java.util.Formatter$FormatSpecifier.(Formatter.java:2643)
at java.util.Formatter.parse(Formatter.java:2480)
at java.util.Formatter.format(Formatter.java:2414)
at java.io.PrintStream.format(PrintStream.java:920)
at java.io.PrintStream.printf(PrintStream.java:821)
at Exercise6_25.main(Exercise6_25.java:55)
import java.util.Scanner;
public class matrixCalc
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
int i,j,k;
int n=3;
double a[][]= new double[n][n];
double b[][]= new double[n][n];
double c[][]= new double[n][n];
System.out.println("enter the array elements of a:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=s.nextDouble();
}
System.out.print(" ");
}
System.out.println(" ");
System.out.println("enter the array elements of b:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=s.nextDouble();
}
System.out.print(" ");
}
System.out.println(" ");
System.out.println("the result matrix is:");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.printf("%.2d", c[i][j]+" ");
}
System.out.println();
}
}
}
You are using the
%dspecifier, which requires an integer argument — but you are giving it aString(becausec[i][j]+" "convertsc[i][j]toStringwhen concatenating it).Also, the
%dspecifier does not use a decimal point at all. Since integral types can be implicitly converted to floating-point types, the%fspecifier is what you’re looking for.And finally, the number after the decimal point in the format specifier is what tells it how many decimal places to go to. You say you only want one decimal place, so let’s make that a 1.
So what we end up with is this:
See the
FormatterJavadocs for a (somewhat mind-boggling) description of the all possible format specifiers. (Don’t worry too much if you can’t understand everything there; you’ll never need most of it anyway.)