Java Program to count number of occurrences of each vowel in a file
/* Java program to count the number of occurrences of each vowel i.e. a,e,i,o and u. Supply file name as command line argument */
Program:
import java.io.*;
public class count_vowel
{
public static void printf(String s)
{
System.out.println(s);
}
public static void main(String args[]) throws Exception
{
if(args.length == 0)
{
printf("Please enter file name as command line.");
}
else
{
int ch;
String fname = args[0];
//printf(fname);
try
{
//File f = new File(args[0]);
File f = new File(fname);
FileInputStream fis = new FileInputStream(f);
int a, e, o, u, i;
a=e=o=u=i=0;
printf("File contents: \n");
while(true)
{
ch = fis.read();
if(ch == -1)
break;
System.out.print((char)ch);
if((char)ch == 'a' || (char)ch == 'A')
a++;
else if((char)ch == 'e' || (char)ch == 'E')
e++;
else if((char)ch == 'i' || (char)ch == 'I')
i++;
else if((char)ch == 'o' || (char)ch == 'O')
o++;
else if((char)ch == 'u' || (char)ch == 'U')
u++;
}
printf("Number of occurrences of vowels: ");
printf("a: "+a);
printf("e: "+e);
printf("i: "+i);
printf("o: "+o);
printf("u: "+u);
}
catch(FileNotFoundException fnf)
{
printf("File Not Found.");
}
}
}
}
Output:

Download Source Code:
Program:
import java.io.*;
public class count_vowel
{
public static void printf(String s)
{
System.out.println(s);
}
public static void main(String args[]) throws Exception
{
if(args.length == 0)
{
printf("Please enter file name as command line.");
}
else
{
int ch;
String fname = args[0];
//printf(fname);
try
{
//File f = new File(args[0]);
File f = new File(fname);
FileInputStream fis = new FileInputStream(f);
int a, e, o, u, i;
a=e=o=u=i=0;
printf("File contents: \n");
while(true)
{
ch = fis.read();
if(ch == -1)
break;
System.out.print((char)ch);
if((char)ch == 'a' || (char)ch == 'A')
a++;
else if((char)ch == 'e' || (char)ch == 'E')
e++;
else if((char)ch == 'i' || (char)ch == 'I')
i++;
else if((char)ch == 'o' || (char)ch == 'O')
o++;
else if((char)ch == 'u' || (char)ch == 'U')
u++;
}
printf("Number of occurrences of vowels: ");
printf("a: "+a);
printf("e: "+e);
printf("i: "+i);
printf("o: "+o);
printf("u: "+u);
}
catch(FileNotFoundException fnf)
{
printf("File Not Found.");
}
}
}
}
Output:
Download Source Code:
Comments
Post a Comment