Thursday 21 January 2016

Java program to count occurrence of each word in a file

Question:


Write a program to display frequency count of each word in a file. Filename will be provided by user.

Desired Output:

Enterfilname: 
A.txt

the 2
is 3..

Source code: 


import java.io.*;
import java.util.*;
class AB
{
public static void main(String args[]) throws IOException
{
//Entering file name
System.out.println("Enter File name along with path: ");
Console con=System.console();

//getting all unique tokens
StreamTokenizer st=new StreamTokenizer(new FileInputStream(con.readLine()));
HashSet set=new HashSet();
while(st.nextToken() != StreamTokenizer.TT_EOF)
{
switch(st.ttype)
{
case StreamTokenizer.TT_WORD:
set.add(st.sval+"");
break;
case StreamTokenizer.TT_NUMBER:
set.add(st.nval+"");
break;
}
}

//searching for number of time each token occured
HashMap map=new HashMap();
Iterator itr=set.iterator();
while(itr.hasNext())
{
String s=(String)itr.next();
int counter=0;
StreamTokenizer st1=new StreamTokenizer(new FileInputStream("abc.txt"));
while(st1.nextToken() != StreamTokenizer.TT_EOF)
{
if(s.equals(st1.sval) || s.equals(st1.nval+"")) counter++;

}
map.put(s,counter);
}

//printing output
Set set1=map.keySet();
itr=set1.iterator();
while(itr.hasNext())
{
String s1=(String)itr.next();
System.out.println(s1+"\t"+map.get(s1));
}
}
}

Tuesday 12 January 2016

Java program for Stack implementation using vectors

Source Code:

import java.util.*;
class UnderFlowException extends Exception
{
public UnderFlowException(String s)
{
super(s);
}
}
class MyStack
{ private int i;
Vector v;
public MyStack()
{
i=-1;
v= new Vector();
}
public void push(Object o)
{

v.add(++i,o);
}
public Object pop() throws UnderFlowException
{
if(i>=0)
return v.get(i--);
else
{
UnderFlowException e=new UnderFlowException("** Stack Overflow **");
throw e;
}
}
public boolean empty()
{
return(i==-1);
}
}

Monday 11 January 2016

Java program to merge Splitted files into a single files

In this program we assume all splitted files are there in a Directory and use is supplying the path of that directory. Also user is specifying desired file name of final file

Source Code:

import java.io.*;
class Merger
{
private String path,name;
public Merger(String p, String n)
{
path=p;
name=n;
}
public void run()
{
try
{
File f= new File(path);
File arr[];
arr=f.listFiles();
FileOutputStream fos=new FileOutputStream(path+"/"+name);
for(int i=0;i<arr.length;i++)
{
FileInputStream fis=new FileInputStream(arr[i]);
int ch;
while((ch=fis.read()) != -1)
{
fos.write(ch);
}
fis.close();
}
fos.close();
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
}
class N
{
public static void main(String args[])
{
Console con=System.console();
System.out.println("Enter the Directory Path: ");
String s=con.readLine();
System.out.println("Enter the desired output file name with extension: ");
String l=con.readLine();
Merger f=new Merger(s,l);
f.run();
}
}

Java program to Split a file into multiple files

In this program we split a given file into multiple files of desired(less than original file) size. This program can be practically useful for transferring files when we do not have portable device of sufficient capacity. In this we ask user to enter the pathname of file and desired output file size.

Source Code:


import java.io.*;
class FileSplit
{
private String name,path,gname;
private long nsize,size,n=0;
public FileSplit(String pn,int i )
{
name=pn;
nsize=i;
}
public void run()
{
try
{
FileInputStream fis=new FileInputStream(name);
File f=new File(name);
size=f.length(); //calc size of input file
System.out.println("\nLength "+size);
path=f.getParent();
long d=0;
while(size>=d) //no.of files
{
n++;
d=d+nsize;
}
System.out.println("\nNumber of Files created: "+n);
int ch;
gname=f.getName();
for(int i=0;i<n;i++)
{
System.out.println(path+"\\"+i+"."+gname);
FileOutputStream fos=new FileOutputStream(path+"\\"+i+"."+gname);
while((ch=fis.read()) != -1)
{
fos.write(ch);
if(new File(path+"\\"+i+"."+gname).length()==nsize)
{
fos.close();
break;
}
}
}
fis.close();
f.delete();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
class M
{
public static void main(String args[]) throws Exception
{
Console con=System.console();
System.out.println("Enter the fileName with Path: ");
String s=con.readLine();
System.out.println("Enter the fidesired file size(in bytes): ");
int l=Integer.parseInt(con.readLine());

FileSplit f=new FileSplit(s,l);
f.run();
}
}

Tuesday 15 December 2015

Exception case in which explicit typecasting is not required in narrowing in Java ( Using Final Keyword )

We all know that in case of narrowing (conversion of higher range data type into lower) explicit typecasting is required. But here is an exception case in which we do not have to explicit typecast in case of narrowing.

1. Int to byte 

Without using final keyword

int i=10;
byte b=i;

Above code will give throw a compile time error as int cannot be assigned to byte. For above program to rum we need to explicitly typecast int to byte.

int i=10;
byte b=(int)i;

This time program will run without giving any error message

Using final keyword

final int i=10;
byte b=i;

In this case

Wednesday 9 December 2015

Java program to count Number of words in a entered String

This is a program to count number of Words in a Entered String.

Source Code:

import java.io.*;
class Count
{
public static void main(String args[])
{
String s;
int count=0;
System.out.print("Enter a String: ");
Console con=System.console();
s=con.readLine();
char arr[]=s.toCharArray();
for(int i=0;i<arr.length;i++)
{
if(arr[i]==' ')
count++;
}
System.out.print("There are "+(count+1)+" words in Entered String");
}
}

Logic:We know that there is one blank space in between two words. Using the same fact we have created  the program in which we count number of spaces and increase it by 1 in final result.

Output:


Java Program to check weather a Entered String is palindrome or not

Here is a java program to check weather a Entered String is palindrome or not. In this program we will ask user to enter a string and will check if it is palindrome. 
palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.

Source Code: 


import java.io.*;
class Palindrome
{
public static void main(String args[])
{
String s;
System.out.print("Enter a String: ");
Console con=System.console();
s=con.readLine();
char arr[];
arr=s.toCharArray();
char arr2[]=new char[arr.length];
for(int i=arr.length-1,j=0;i>=0;i--,j++)
{
arr2[j]=arr[i];
}
String s2;
s2=String.copyValueOf(arr2);
if(s.equalsIgnoreCase(s2))
{
System.out.println("Entered String is pallindrome");
}
else
{
System.out.println("Entered String isn't pallindrome");
}
}
}

Output: