Friday 19 August 2016

Java Tutorial : Java IO (Scanner class use Locale)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=w-7IcAPVPXo&list=UUhwKlOVR041tngjerWxVccw

myfile.txt
8.5
32,767
3.14159
1,000,000.1
ScannerDemo.java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Locale;
import java.util.Scanner;

public class ScannerDemo
{

    public static void main(String[] args) throws FileNotFoundException
    {
        Scanner scanner = null;
        double sum = 0;

        try
        {
            scanner = new Scanner(new BufferedReader(new FileReader(
                                                        "myfile.txt")));
            /*
             * Sets this scanner's locale to the specified
             * locale.
             * 
             * We have to mention the locale, because
             * thousands separators and decimal symbols are
             * locale specific. So, the this example would
             * not work correctly in all locales if we
             * didn't specify that the scanner should use
             * the US locale.
             */
            scanner.useLocale(Locale.US);

            while (scanner.hasNext())
            {
                if (scanner.hasNextDouble())
                {
                    double doubleValue = scanner.nextDouble();
                    System.out.println("doubleValue = " + doubleValue);
                    sum += doubleValue;
                }
                else
                {
                    scanner.next();
                }
            }
        }
        finally
        {
            if (scanner != null)
            {
                scanner.close();
            }
        }

        System.out.println("sum = " + sum);
    }
}
Output
doubleValue = 8.5
doubleValue = 32767.0
doubleValue = 3.14159
doubleValue = 1000000.1
sum = 1032778.74159

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_Scanner_locale_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/JavaIODemo_Scanner_locale_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/16638d65b46bec1088dab744ba69a31424c4a14f/BasicJava/JavaIODemo_Scanner_locale_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment