package practice;
import java.util.*;
import java.util.ArrayList;
import java.util.Iterator;
public class Practice {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
StringBuilder output = new StringBuilder();
System.out.println("Enter the number of rows & columns: ");
System.out.print("Enter the number of rows: ");
int row = input.nextInt();
System.out.print("Enter the number of columns: ");
int columns = input.nextInt();
int [][]nums = new int[row][columns];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < columns; j++)
{
System.out.print("Number " + (j + 1) + ": ");
nums[i][j] = input.nextInt();
output.append("\n").append(nums[i][j]);
}
System.out.println( " " );
}
System.out.println(output);
}
}
我对上面显示的代码有疑问,我正在练习多维数组。我想要的是制作一个由行和列分隔的数字列表,例如:如果我在行中输入3而在列中输入4,则输出数字应该像这样排列。
10 20 30 40
50 60 70 80
90 100 101 102
但问题是输出显示是一长串连续数字。 任何人都可以帮我解决这个问题,
谢谢,
答案 0 :(得分:3)
切换到下一行时,您必须在输出中添加一个新行:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
StringBuilder output = new StringBuilder();
System.out.println("Enter the number of rows & columns: ");
System.out.print("Enter the number of rows: ");
int row = input.nextInt();
System.out.print("Enter the number of columns: ");
int columns = input.nextInt();
int[][] nums = new int[row][columns];
for (int i = 0; i < row; i++) {
for (int j = 0; j < columns; j++) {
System.out.print("Number " + (j + 1) + ": ");
nums[i][j] = input.nextInt();
output.append(" ").append(nums[i][j]);
}
output.append("\n");
System.out.println("\n");
}
System.out.println(output);
}
答案 1 :(得分:0)
您可能希望在外部循环中添加新行,如下所示:
for (int i = 0; i < row; i++)
{
for (int j = 0; j < columns; j++)
{
System.out.print("Number " + (j + 1) + ": ");
nums[i][j] = input.nextInt();
output.append(nums[i][j]);
}
output.append("\n");
}
答案 2 :(得分:0)
将嵌套for循环内容更改为
for (int i = 0; i < row; i++)
{
for (int j = 0; j < columns; j++)
{
System.out.print("Number " + (j + 1) + ": ");
nums[i][j] = input.nextInt();
output.append(nums[i][j]).append(" ");
}
System.out.println();
output.append("\n");
}