有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何用Scanner处理多行输入

我必须处理的输入:

2
2 3
3 3

我的代码:

Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();

int[][] array = new int[size][2];
Scanner scanner2 = new Scanner(System.in);

for (int i=0; i<size; i++) {
    for (int j=0; j<2; j++) {
        array[i][j] = scanner2.nextInt();
    }
}

2是输入包含的对数。我想把这些对放在2D数组中,但我需要先得到2来声明数组的大小。上面的代码在NetBeans中运行良好,我提供了如下输入:

number 
enter 
pair 
enter
...

但所有的数字都以我上面发布的格式汇集在一起

有什么帮助吗


共 (1) 个答案

  1. # 1 楼答案

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in).useDelimiter("\\n");
        System.out.println("Enter an integer");
        int size = scanner.nextInt();
    
        int[][] array = new int[size][2];
    
        for (int i = 0; i < size; i++) {
            String myInt = scanner.next();
            String[] myInts = myInt.split(" ");
            for (int j = 0; j < 2; j++) {
                array[i][j] = Integer.parseInt(myInts[j]);
            }
        }
        // print contents
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.println("[" + i + "]" + "[" + j + "] = " +array[i][j]);
            }
        }        
    }