我正在尝试编写一个程序,该程序首先接收转置大小(n X n)的输入,然后接受矩阵元素的输入,但是我需要元素为双精度而不是整数,并且我保持得到一个错误(我应该将double替换为int)。我该如何解决?我是一名新的Java学习者。提前谢谢这是我的代码:
import java.util.Scanner;
public class transpose_test {
public static void main(String args[]) {
int tra_size;
Scanner sc=new Scanner(System.in);
System.out.print("What size does the transpose have (n X n): ");
tra_size=sc.nextInt();
int a[][]=new int[tra_size][tra_size];
System.out.println("Input the elements of matrix (a):");
for(double i=0; i<tra_size; i++) {
for(double j=0; j<tra_size; j++) {
System.out.print("a [" + (i) + "],[" + (j) + "] = ");
a[i][j] = sc.nextDouble(); // Keeps telling me to chanege the double into int
}
}
System.out.println("Matrix a:");
for(double i=0; i<tra_size; i++){
for(double j=0; j<tra_size; j++){
System.out.print(a[i][j] + "\t");
}
System.out.print("\n");
}
System.out.println("The Transpose Matrix is");
for(double i=0; i<tra_size; i++){
for(double j=0; j<tra_size; j++){
System.out.print(a[j][i] + "\t");
}
System.out.print("\n");
}
}
}
对于for循环,您正在检查从0到矩阵大小。那应该是int
。问题是您的2d数组类型。如果需要double
数据类型的元素,则需要将该数组声明为double
。
double a [][]=new double [tra_size][tra_size]
尝试此代码。这样可以解决您的问题
int tra_size;
Scanner sc=new Scanner(System.in);
System.out.print("What size does the transpose have (n X n): ");
tra_size=sc.nextInt();
double a [][]=new double [tra_size][tra_size];
System.out.println("Input the elements of matrix (a):");
for(int i=0; i<tra_size; i++) {
for(int j=0; j<tra_size; j++) {
System.out.print("a [" + (i) + "],[" + (j) + "] = ");
a[i][j] = sc.nextDouble(); // Keeps telling me to chanege the double into int
}
}
System.out.println("Matrix a:");
for(int i=0; i<tra_size; i++){
for(int j=0; j<tra_size; j++){
System.out.print(a[i][j] + "\t");
}
System.out.print("\n");
}
System.out.println("The Transpose Matrix is");
for(int i=0; i<tra_size; i++){
for(int j=0; j<tra_size; j++){
System.out.print(a[j][i] + "\t");
}
System.out.print("\n");
}
我思考我看到了困惑,数组的indices >>不应为double
(它们应为int
)。数组a
的元素应为double
(double[][]
而非int[][]
)。喜欢,
Scanner sc = new Scanner(System.in);
System.out.print("What size does the transpose have (n X n): ");
int tra_size = sc.nextInt();
double[][] a = new double[tra_size][tra_size];
System.out.println("Input the elements of matrix (a):");
for (int i = 0; i < tra_size; i++) {
for (int j = 0; j < tra_size; j++) {
System.out.printf("a [%d],[%d] = ", i, j);
a[i][j] = sc.nextDouble();
}
}
System.out.println("Matrix a: ");
for (int i = 0; i < tra_size; i++) {
for (int j = 0; j < tra_size; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
System.out.println("The Transpose Matrix is");
for (int i = 0; i < tra_size; i++) {
for (int j = 0; j < tra_size; j++) {
System.out.print(a[j][i] + "\t");
}
System.out.println();
}
您需要明确两件事: