Sunday 7 February 2016

Write a program which find the occurrence of substring in string ?

package test;

public class substring {

public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "helloslkhellodjladfjhello";
    String findStr = "hello";
    int lastIndex = 0;
    int count = 0;

    while (lastIndex != -1) {

   
    System.out.println("first "+lastIndex);
    if (lastIndex != -1) {
    count++;
    lastIndex += findStr.length();
   
    }
    }
    System.out.println("number of substring"+count);

}

}

Write a program to closest prime number to any input number ?

package test;
import java.util.*;

public class closestprime {
public static boolean isprime(int a)
{int c=0;
for(int i=2;i<a/2;i++)
{
if(a%i==0)
{
c=1;
}
}

if(c==1)
         return false;
else
return true;


}

public static void main(String[] arg)
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int i;
int n,n1,d,d1;
for(i=a+1;;i++)
{
if(isprime(i))
{    n=i;
    d=i-a;

break;
}
}
for(i=a-1;;i--)
{
if(isprime(i))
{    d1=a-i;
n1=i;

break;
}
}
if(d>d1)
System.out.println("closest prime no.: "+n1);
else if(d1>d)
System.out.println("closest prime no.: "+n);
else
System.out.println("closest prime no.: "+n+" "+n1);
}

}

Tuesday 2 February 2016

Link List in Java

package test;
import java.util.*;

public class linklist<s> {
public node<s> head=null;

public void add()
{Scanner sc=new Scanner(System.in);
s a=(s) sc.nextLine();
head=new node<s>(a,head);
}
public void insert(int n,s b)
{node<s> temp=head;

for(int i=0;i<n;i++)
{
temp=temp.next;
}
temp.next=new node<s>(b,temp.next);

}
public void show()
{node<s> temp = head;
while(temp!=null)
{
System.out.println(temp.data);
temp=temp.next;

}
}
public class node<s>
{
s data;
node<s> next;
node(s a,node next)
{
this.data=(s) a;
this.next=next;
}
}
public static void main(String[] arg)
{

linklist<String> l=new linklist<String>();
for(int i=0;i<3;i++)
{
 l.add();
}

l.insert(2,"d");

l.show();
}


}