Java Scanner read input via try-with-resources block

Introduction

We can read input from Scanner via try-with-resources block in Java.

try (Scanner src = new Scanner(fin)) {
      // Read and sum numbers.
      while (src.hasNext()) {
        if (src.hasNextDouble()) {
          sum += src.nextDouble();/*from w ww . ja  v  a  2 s.c o  m*/
          count++;
        } else {
          String str = src.next();
          if (str.equals("done"))
            break;
          else {
            System.out.println("File format error.");
            return;
          }
        }
      }
}

Full source


import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main {
  public static void main(String args[]) throws IOException {

    int count = 0;
    double sum = 0.0;

    // Write output to a file.
    FileWriter fout = new FileWriter("test.txt");
    fout.write("2 3.4 5 6 7.4 9.1 10.5 done");
    fout.close();//  w  w  w . j  a  v a  2s.com

    FileReader fin = new FileReader("test.txt");

    try (Scanner src = new Scanner(fin)) {
      // Read and sum numbers.
      while (src.hasNext()) {
        if (src.hasNextDouble()) {
          sum += src.nextDouble();
          count++;
        } else {
          String str = src.next();
          if (str.equals("done"))
            break;
          else {
            System.out.println("File format error.");
            return;
          }
        }
      }
    }
    System.out.println("Average is " + sum / count);
  }
}



PreviousNext

Related