在Java 8中从控制台读取文本

时间:2019-03-09 13:31:58

标签: java java-8

我在控制台中有2行,其中第一行是数组大小,第二行是数组中的元素,并且元素按空间划分。 我需要将这些元素读取为Integer并将其作为数组传递给函数,例如getInput(int [] nums)。

Ex:
5
1 2 2 3 3

如何在Java 8中使用缓冲读取器来做到这一点?

我尝试了下面的代码,但这不是我期望的。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int t = Integer.parseInt(br.readLine());
System.out.println("Array Size:" + t);
int input[] = new int[t];

for (int i = 0; i < t; i++) {
    input[i] = Integer.parseInt(br.readLine());
}

for (int i = 0; i < input.length; i++) {
    System.out.println(input[i]);
}

1 个答案:

答案 0 :(得分:0)

为什么不只使用扫描仪?您可以使用Scanner.nextLine()阅读这两行。例如:

import java.util.*;  
public class ScannerClassExample {    
    public static void main(String args[]){
        //Make a new Scanner reading the System input
        Scanner scanner = new Scanner(System.in);
        //Read the first line
        String arraySize = scanner.nextLine();
        //Read the elements and split on spaces
        String elementsLine = scanner.nextLine();
        String[] elements = elementsLine.split(" ");
        //If you want them to be integers, you could use this
        int[] intElements = new int[elements.length];
        for (int i = 0; i < elements.length; i++) {
            intElements[i] = Integer.parseInt(elements[i]);
        }
        scanner.close();
    }
}

如果您使用此选项,我也建议您使用scanner.hasNext()。寻找有关此的示例。

希望这会有所帮助。