How to read multiple integer values from one line in Java using BufferedReader object?

前端 未结 9 2237
萌比男神i
萌比男神i 2021-02-06 15:39

I am using BufferedReader class to read inputs in my Java program. I want to read inputs from a user who can enter multiple integer data in single line with space. I want to rea

9条回答
  •  伪装坚强ぢ
    2021-02-06 16:19

    Integer.parseInt(br.readLine()) -> Reads a whole line and then converts it to Integers.

    scanner.nextInt() -> Reads every single token one by one within a single line then tries to convert it to integer.

    String[] in = br.readLine().trim().split("\\s+"); 
    // above code reads the whole line, trims the extra spaces 
    // before or after each element until one space left, 
    // splits each token according to the space and store each token as an element of the string array.
    
    
    for(int i = 0; i < n; i++)
        arr[i] = Integer.parseInt(in[i]);
    
    // Converts each element in the string array as an integer and stores it in an integer array.
    

提交回复
热议问题