Posts Tagged scanner
Scanner to read various types of data from a file.
This example shows how to use scanner to read various type(like integer, double, boolean, string) of data from a file.
import java.util.*;
import java.lang.io.*;
class ScanMixed{
public static void main(String a[]) throws IOException {
int i;
double d;
boolean b;
String str;
//Write output to a file
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);
// Read to end.
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();
}
}
Scanner to read double numbers from a file and display their average.
It uses scanner to read double numbers from a file and display their average. It is assumed that input is terminated by the string “done”.
import java.util.*;
import java.io.*;
class AvgFile{
public static void main(String a[]) throws IOException{
int count =0;
double sum=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();
FileReader fin= new FileReader ("Test.txt");
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("ERROR");
return;
}
}
}
fin.close();
System.out.println("Average is " +sum/ count);
}
}
Scanner to read double numbers from keyboard and display their average.
It uses scanner to read double numbers from keyboard and display their average. It is assumed that input is terminated by the string “done”.
import java.util.*;
class AvgNums{
public static void main (String a[]){
Scanner conin = new Scanner (System.in);
int count =0;
double sum=0.0;
System.out.println("Enter Numbers:: ");
// Read and Sum numbers
while (conin.hasNext() ) {
if(conin.hasNextDouble () ) {
sum += conin.nextDouble();
count++;
}
else {
String str = conin.next();
if(string.equals ("done")) break;
else {
System.out.println("ERROR");
return;
}
}
}
System.out.println("Average is "+ sum/ count);
}
}


Recent Comments