gpt4 book ai didi

Java 从主函数调用打印方法并使用来自另一个单独方法的数据

转载 作者:行者123 更新时间:2023-12-02 09:22:33 26 4
gpt4 key购买 nike

我正在尝试运行一个程序,该程序根据用户输入构造一个二维数组,然后打印该数组。必须使用一种方法构造数组并使用单独的方法打印行。我只想在新行上打印数组中的每一行。我不知道如何将数组从一种方法拉到另一种方法中。

代码已设置,因此当调用 main 方法时,它将调用“构造函数”方法来构建数组,然后在构建数组后,它将获取该数组并发送将数据传递给 print 方法来打印每一行。我不确定从代码中的位置开始,我仍然不明白如何从不同的方法中提取数据。

package workfiles;

import java.util.*;
import java.util.Scanner;

public class hw2
{
// Do not modify this method
public static void main(String[] args)
{
try {
int[][] iArray = enter2DPosArray();
System.out.println("The original array values:");
print2DIArray(iArray);

int[][] tArray = transposition(iArray);
System.out.println("The transposed array values:");
print2DIArray(tArray);
} catch (InputMismatchException exception) {
System.out.println("The array entry failed. The program will now halt.");
}
}

// A function that prints a 2D integer array to standard output
// THIS METHOD IS THE ONE THAT IS SUPOSED TO PRINT THE ROWS ON NEW LINES
public static void print2DIArray(int[][] output)
{
int[][] iArray;

for (int row = 0; row < iArray.length; row++) {
for (int column = 0; column < iArray[row].length; column++) {
System.out.print(iArray[row][column] + " ");
}
System.out.println();
}
}

// A function that enters a 2D integer array from the user
// It raises an InputMismatchException if the user enters anything other
// than positive (> 0) values for the number of rows, the number of
// columns, or any array entry
public static int[][] enter2DPosArray() throws InputMismatchException
{
int row = 0, col = 0, arow = 0, acol = 0, holder;

Scanner numScan = new Scanner(System.in);

while (row <= 0) {
System.out.print("How many rows (>0) should the array have? ");
row = numScan.nextInt();
}

while (col <= 0) {
System.out.print("How many columns (>0) should the array have? ");
col = numScan.nextInt();
}

int[][] iArray = new int[row][col];

while (arow < row) {
while (acol < col) {
System.out.println("Enter a positive (> 0) integer value: ");
holder = numScan.nextInt();
iArray[arow][acol] = holder;
acol++;
}

if (acol >= col) {
acol = 0;
arow ++;
}
}

//arrayName[i][j]
numScan.close();
return iArray;
}

public static int[][] transposition(int[][] iArray)
{
int r = 0, c = 0;

int[][] transpose = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
transpose[i][j] = iArray[j][i];
}
}
return transpose;
}
}

最佳答案

public static void print2DIArray(int[][] output) {    
int[][] iArray;
for (int row = 0; row < iArray.length; row++) {

当您调用 print2DIArray 方法时,您正在尝试迭代刚刚创建的空数组。我认为您想迭代传入的“输出”参数。

关于Java 从主函数调用打印方法并使用来自另一个单独方法的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41743675/

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