gpt4 book ai didi

java 矩阵 0's and 1' s

转载 作者:行者123 更新时间:2023-11-29 09:28:35 24 4
gpt4 key购买 nike

大家好,这是我的家庭作业问题:编写一个方法,使用以下标题在对话框中显示 n × n 矩阵:public static void printMatrix(int n)

矩阵中的每个元素都是0或1,是随机生成的。一个 3 x 3 的矩阵可能看起来像这样:

0 1 0

0 0 0

1 1 1

到目前为止,我可以很容易地在扫描仪中打印出我的问题,但是我不确定如何在对话框中打印出来。

目前我收到错误:错误:此处不允许使用 'void' 类型 JOptionPane.showMessageDialog(null, printMatrix(n));1 个错误

我知道它是无效的,不能返回,但是我的任务要求该方法是无效的。我真正的问题是我将如何在方法中打印它?我已经在这个问题上工作了 4 个小时,这真的让我很沮丧。

import java.util.*;
import java.lang.*;
import java.io.*;
import javax.swing.JOptionPane;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
// Main method
public static void main(String[] args)
{
// Prompt user to enter numbers
String stringInteger = JOptionPane.showInputDialog(null, "Enter a integer n to determine the size of matrix: ", "Size of Matrix Input", JOptionPane.INFORMATION_MESSAGE);

// Convert string to integer
int n = Integer.parseInt(stringInteger);
JOptionPane.showMessageDialog(null, printMatrix(n));
}

// Generate and display random 0's and 1's accordingly
public static void printMatrix(int n)
{
// Row depending on n times
for (int row = 0; row < n; row++)
{
// Column depending on n times
for (int col = 0; col < n; col++)
{
String randomN = ((int)(Math.random() * 2)+ " ");
}
}

}
}

最佳答案

我想你被要求打印。另外,我更喜欢 Random.nextBoolean()用于生成角色。循环并调用 System.out.print。类似的东西,

public static void printMatrix(int n) {
Random rand = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(rand.nextBoolean() ? "1 " : "0 ");
}
System.out.println();
}
}

public static void main(String[] args) {
printMatrix(3);
}

如果您真的想要使用 JOptionPane你可以使用 StringBuilder构建矩阵并然后显示它。类似的东西,

public static void printMatrix(int n) {
Random rand = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sb.append(rand.nextBoolean() ? "1 " : "0 ");
}
sb.append(System.lineSeparator());
}
JOptionPane.showMessageDialog(null, sb.toString());
}

但是 void 方法不返回任何东西,所以你不能在调用者中打印 void 方法的结果。

关于java 矩阵 0's and 1' s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35965076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com