gpt4 book ai didi

java - 如何将一维数组转换为二维数组

转载 作者:行者123 更新时间:2023-11-30 05:17:04 25 4
gpt4 key购买 nike

我已经有了如何将二维转换为一维的代码,但我不知道如何反之亦然。这是我的代码:

package laboratorio9;

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
int A[][];
int B[];
int n;
int m;
int nb = 0;

System.out.println("Enter the number of lines in your array.");
n = entrada.nextInt();

System.out.println("Enter the number of columns in your array.");
m = entrada.nextInt();

A = new int[m][n];
B = new int[m*n];

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.println("Enter A["+i+"]["+j+"]");
A[i][j] = entrada.nextInt();
}
}
System.out.println();

for (int i = 0; i < m;i++) {
for (int j = 0; j < n; j++) {
B[nb] = A[i][j];
nb++;
}
}

for (int i = 0; i < m*n; i++) {
System.out.println(B[i] + " ");
}
System.out.println();

Boolean Swap = false;

do {
Swap = false;
for (int i=0;i<B.length-1;i++)
if (B[i] > B[i + 1]) {
int Temp = B[i];
B[i] = B[i + 1];
B[i + 1] = Temp;
Swap = true;
}
} while (Swap);

for (int i=0;i<B.length;i++)
System.out.println(B[i]);
}
}

最佳答案

您正在寻找类似的内容:

int j = 0;
int k = 0;
for ( int i = 0; i < nb;i++)
{
C[j][k] = B[i];
k++;
if( k >= n )
{
j++;
k = 0;
if( j >= m )
throw Error();
}
}

这与:

相同
int k = 0;
for ( int i = 0; i < m;i++)
{
for ( int j = 0; j < n;j++)
{
C[i][j] = B[k++];
}
}

但试图帮助更多地解释这个概念。

关于java - 如何将一维数组转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/664927/

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