reading input till EOF in java

后端 未结 10 629
后悔当初
后悔当初 2020-12-09 06:35

In C++ if I wish to read input till the EOF I can do it in the following manner

while(scanf(\"%d\",&n))
{
    A[i]=n;
    i++;
}

I can

相关标签:
10条回答
  • 2020-12-09 06:47

    You can do this:

    Scanner s = new Scanner(System.in);
    while (s.hasNextInt()) {
        A[i] = s.nextInt();
        i++;
    }
    
    0 讨论(0)
  • 2020-12-09 06:47
    Scanner scanner = new Scanner(System.in);
    int c = 0;
    while(scanner.hasNext()){
      System.out.println(++c + " " + scanner.nextLine());
    }
    scanner.close();
    // use while instead of normal for loop. 
    // If you need to read a file than BufferReader is the best way to do it, as explained above.
    
    0 讨论(0)
  • 2020-12-09 06:53
     import java.io.BufferedReader;
     import java.io.FileReader;
    
    BufferedReader br = null;  
         br = new BufferedReader(new FileReader(file));
           while ((line = br.readLine()) != null) {              
    
         }
    
        //using Scanner class
    
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
          String line = scanner.nextLine();
          System.out.println(line);
       }
    
    0 讨论(0)
  • 2020-12-09 06:56
    // assuming that reader is an instance of java.io.BufferedReader
    String line = null;
    while ((line = reader.readLine()) != null) {
        // do something with every line, one at a time
    }
    

    Let me know if you run into difficulties.

    0 讨论(0)
提交回复
热议问题