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
但问题是输出显示的是一长串连续数字。
谁能帮我解决这个问题,
谢谢,
最佳答案
切换到下一行时,您必须在输出中添加一个新行:
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);
}
关于java - 使用 Scanner 的多维数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41719671/