我試圖運行一個程序,該程序從用戶輸入構造一個2D數組,然後打印該數組。該數組必須在一個方法中構造並以單獨的方法打印行。我只打算在新行上打印數組中的每一行。我不知道如何將數組從一種方法拉到另一種方法。Java從一個主函數調用打印方法並使用來自另一個單獨方法的數據
代碼被設置成當main
方法被調用它會調用「構造」的方法來構建數組,然後數組建成後它就會採取陣列和數據發送到打印方法打印每一行。我不確定從代碼中的哪個位置開始,但我仍然不明白如何從不同的方法提取數據。
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;
}
}
謝謝!即時通訊不知道我是如何錯過了,生病標記這個答案,當我可以 –
不用擔心。快樂的javaing – Christy