Java - File Input Output Scanner class

Introduction

Scanner class in java.util package reads and parses a text, based on a pattern, into primitive types and strings.

The source can be an InputStream, a file, a String object, or a Readable object.

You can use a Scanner object to read primitive type values from the standard input System.in.

Scanner class has many methods named liked hasNextXxx() and nextXxx(), where Xxx is a data type, such as int, double, etc.

The hasNextXxx() method checks if the next token from the source can be interpreted as a value of the Xxx type.

nextXxx() method returns a value of a particular data type.

The following code show how to use the Scanner class by building a calculator to perform addition, subtraction, multiplication, and division.

Demo

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    // Read three tokens from the console: operand-1 operation operand-2
    System.out.print("input something like 1 + 2");

    // Build a scanner for the standard input
    Scanner scanner = new Scanner(System.in);
    double n1 = Double.NaN;
    double n2 = Double.NaN;
    String operation = null;//from  w ww.j a v  a2  s. co  m

    try {
      n1 = scanner.nextDouble();
      operation = scanner.next();
      n2 = scanner.nextDouble();

      double result = calculate(n1, n2, operation);
      System.out.printf("%s %s %s = %.2f%n", n1, operation, n2, result);
    } catch (Exception e) {
      System.out.println("An invalid expression.");
    }
  }

  public static double calculate(double op1, double op2, String operation) {
    switch (operation) {
    case "+":
      return op1 + op2;
    case "-":
      return op1 - op2;
    case "*":
      return op1 * op2;
    case "/":
      return op1 / op2;
    }

    return Double.NaN;
  }
}

Result