use Scanner to read input that contains several different types of data : Scanner « Development Class « Java






use Scanner to read input that contains several different types of data

  

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

class ScanMixed {
  public static void main(String args[]) throws IOException {
    int i;
    double d;
    boolean b;
    String str;

    FileWriter fout = new FileWriter("test.txt");
    fout.write("Testing Scanner 10 12.2 one true two false");
    fout.close();

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

    Scanner src = new Scanner(fin);

    while (src.hasNext()) {
      if (src.hasNextInt()) {
        i = src.nextInt();
        System.out.println("int: " + i);
      } else if (src.hasNextDouble()) {
        d = src.nextDouble();
        System.out.println("double: " + d);
      } else if (src.hasNextBoolean()) {
        b = src.nextBoolean();
        System.out.println("boolean: " + b);
      } else {
        str = src.next();
        System.out.println("String: " + str);
      }
    }

    fin.close();
  }
}

   
  








Related examples in the same category

1.Read int by using Scanner Class
2.Use Scanner to read user input
3.Count all vowels inputed from keyboard
4.Use Scanner to compute an average of the values
5.Use Scanner to compute an average of the values in a file
6.Use Scanner to read various types of data from a file
7.Use Scanner to compute an average a list of comma-separated values
8.Demonstrate findInLine()
9.Letting the user decide when to quit
10.Test the input string in the while condition.
11.This program demonstrates console input.
12.Reading double value from console with ScannerReading double value from console with Scanner