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

前端 未结 9 2239
萌比男神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:29

    i/p:34 54

     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                                                                            
     StringTokenizer st = new StringTokenizer(br.readLine()," ");
     for(int i=0;i<st.countTokens();i++){
       a=Integer.parseInt(st.nextToken());
       b=Integer.parseInt(st.nextToken());
     }
    

    //For fast input output for one line

    0 讨论(0)
  • 2021-02-06 16:30
    import java.io.*;
    public class HelloWorld{
    
         public static void main(String []args){
            int i;
            System.out.println("enter the array element");
            InputStreamReader isr= new InputStreamReader();
            BufferedReader ib= new BufferedReader(isr);
            int a[]=new int [5];
            for(i=0;i<5;i++)
            {
                a[i]= Integer.parseInt(ib.readLine(a[i]));
    
            }
            for(i=0;i<5;i++)
            {
                System.out.println(a[i]);
            }
    
         }
    }
    
    0 讨论(0)
  • 2021-02-06 16:33

    You can use StringTokenizer class of java.util package. The StringTokenizer class allows an application to break a string into tokens. You can use this tokens using nextToken() method of StringTokenizer class.

    You can use following constructor of StringTokenizer:

    StringTokenizer(String str, String delimiter);

    you can use space(" ") as delemeter.

    int a[] = new int[N];
    StringTokenizer st = new StringTokenizer(br.readLine() , " ");
    for(int i=0 ; i<N ; i++) {
        a[i] = Integer.parseInt(st.nextToken());
    }
    
    0 讨论(0)
提交回复
热议问题