Java Scanner输入两个数组

题目

从命令行读入两个数组的长度和数组的值,其中第一行两个数na和nb代表aa和bb数组的长度

代码

import java.util.Scanner;

public class Z {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int na = scanner.nextInt();
        int nb = scanner.nextInt();
        int[] aa = new int[na];
        int[] bb = new int[nb];
        int i = 0;
        while (scanner.hasNext()) {
            aa[i++] = scanner.nextInt();
            if (i == aa.length) {
                break;
            }
        }
        i = 0;
        while (scanner.hasNext()) {
            bb[i++] = scanner.nextInt();
            if (i == bb.length) {
                break;
            }
        }

        for (int j = 0; j < aa.length; j++) {
            System.out.print(aa[j] + " ");
        }
        System.out.println();
        for (int j = 0; j < bb.length; j++) {
            System.out.print(bb[j] + " ");
        }
    }
}

结果

输入:
3 4
1 2 3
1 2 3 4
输出:
1 2 3 
1 2 3 4 

你可能感兴趣的:(JAVA)