我有一个家庭作业,要求我根据用户输入生成一个 n×n 矩阵。 我尝试了几种解决方案,但似乎没有任何效果。我想这对你们许多人来说都是一个相对简单的任务。
这是作业文本: 使用以下签名编写一个显示 n×n 矩阵的方法: public static void printMatrix(int n) 每个元素都是0或1,是随机生成的。编写一个测试程序,提示用户输入 n 并显示一个 n×n 矩阵。
我最新的尝试如下(显然我还没有调用该方法):
import java.util.Scanner;
public class testProgram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Variable Declarations
int n;
Scanner input = new Scanner(System.in);
//Ask User for the Value of n
System.out.print("Enter n: ");
n = input.nextInt();
}
public static String printMatrix(int n){
String result = " ";
for (int x = 0; x < n; x++){
result += "\n";
for (int y = 0; y < n; y++){
result += (int)(Math.random() * 2);
}
}
return result.substring(1);
}
}
最佳答案
您不调用printMatrix
。在 n = input.nextInt();
之后调用 printMatrix(n)
。您可能想在方法本身中打印结果(因为这就是它的名称所暗示的),并将其类型更改为 void,或者在 main 中打印返回的 String。
关于java - n×n 矩阵作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26013386/