java - 使用扫描器的多维数组

标签 java

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 - 使用扫描器的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719671/

相关文章:

java - 在 Java/Android 中找出 UTF-8 字符串中的字符数

java - 我在减少图像闪烁时遇到问题

java - 如何在 Spring Batch Junit 测试中模拟编写器?

java - 处理来自多个平面文件的海量数据,并根据需求转换为 xml 格式

java - 如何在 Java 中针对 XSD 1.1 验证 XML?

java - 在 Java 中将抽象文件转换为字符串

java - HornetQ:从队列中删除所有消息,不适用于队列中的消费者

java - 如何编写没有 for 和 if 语句的代码

java - 为什么我会收到 "com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value:"错误?

java - Android java计算距离sqlite的多个坐标