Go to Top

Saturday 29 October 2011

To print all the keyboard characters using ASCII code

Question 66 : Write a program in Java to all the keyboard characters using ASCII codes.

Java Program :

class all_ascii
{
 static void print()
 {
     for(int i=0;i<256;i++)
     System.out.print((char)i+" - "+i+"\n");
    }
}

To delete a value from an array

Question 65 : Write a program in Java to delete ONE value from an array.

Java Program :

class del
{
 int[] a;
 int n,p=-1;
 del(int[] arr,int num)
 {
     a=arr;
     n=num;
     search();
     del();
    }
    void search()
    {
        for(int i=0;i<a.length;i++)
        {
            if(a[i]==n)
            p=i;
        }
    }
    void del()
    {
        int b;
        if(p!=-1)
        {
            b=a[a.length-1];
            a[a.length-1]=a[p];
            a[p]=b;
            System.out.print("Array : { ");
            for(int i=0;i<a.length-1;i++)
            System.out.print(a[i]+" ");
            System.out.print("}");
        }
        else
        System.out.print("Error 404");
    }
}

Thursday 27 October 2011

To find the frequency of a word in a string

Question 64 : Write a program in Java to find the fifth highest number among a set of numbers taken as input from the user.

Java Program :

import java.io.*;
class high5
{
static int[] a  ;
  static void check()throws IOException
  {
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      int i,k,c,s;
      System.out.print("\fEnter number of inputs : ");
      c=Integer.parseInt(br.readLine());
      if(c<5)
      check();
      a=new int[c];
      for(i=0;i<c;i++)
      {
          System.out.print("\nEnter a number : ");
          a[i]=Integer.parseInt(br.readLine());
    }
    for(i=0;i<c-2;i++)
    {
        for(k=0;k<c-2;k++)
        {
            if(a[k+1]>a[k])
            {
               s=a[k];
               a[k]=a[k+1];
               a[k+1]=s;
            }
        }
    }
    display();
}
static void display()
{
System.out.print("\n5th highest element is : "+a[4]);
}
}

Wednesday 26 October 2011

Happy Diwali


Tuesday 25 October 2011

Constructor Overloading

Demonstration of constructor overloading.

Java Program :

class const_overload
{
    int a,b,c;
    const_overload()
        {
            a=12;
            b=60;
            c=a+b;
        }
    const_overload(int p,int q)
        {
            a=p;
            b=q;
            c=a+b;
        }
    void display()
        {
            System.out.print("Value : "+c);
        }
}

Monday 24 October 2011

Diwali Special

Sorry for being away all this time. This was all due to a faulty internet connnection. Meanwhile, when I was offline for these few days, I was busy developing small but efficient and enjoyable Java programs. Now on the occasion of the hindu festival called Diwali, I am providing all of them in a .zip file for you all. They are as follows :

1: Bank : A Java ATM which is very much error-free and has loads of options.
2: Cups : A game in which you have to find out the position of the ball hidden inside the cups as the cups move.
3: Game : A game in which you have to guess three numbers within a range and if you are lucky and the numbers match with those chosen by the computer, you get awarded with points. Has some difficulty levels.
4: KBC  : A game similar to the TV show Kaun Banega Crorepati hosted by Amitabh Bachchan. Almost similar to the 2011 edition.
5: Tic-Tac-Toe : A game where you play Tic-Tac-Toe with the computer. Keeps you involved in it.

Try them out, show them to your parents, or simply brag about that you have made them all. You'll find the README inside the .zip package. Unzip it and enjoy.

ICSE Java Download

Friday 21 October 2011

To find absolute value of an integer

Question 63 : Write a program in Java to find the absolute value of an integer.

Java Program :

class absolute
{
    static void cal(int a)
    {
        int b=a>0?a:-a;
        System.out.print("The absolute value of '"+a+"' : "+b);
    }
}

Thursday 20 October 2011

Utilities 18 : Time display

Here is again a free utility to the show current time.

Java Program :

import java.util.*;
class time_display
{
     static void time()
    {
        Calendar c=new GregorianCalendar();
        String apm;
        if(c.get(Calendar.AM_PM)==0)
        apm = "AM";
        else
        apm = "PM";
        System.out.print("\fDate : "+c.get(Calendar.DAY_OF_MONTH)+" / "+c.get(Calendar.MONTH)+" / "+c.get(Calendar.YEAR));
        System.out.print("\n\nTime : "+c.get(Calendar.HOUR)+" : "+c.get(Calendar.MINUTE)+" : "+c.get(Calendar.SECOND)+" "+apm);
        try{Thread.sleep(1000);}
        catch(Exception e){}
        time();
    }
}

Utilities 17 : Reflection

This will help you to find the reflected point in x-axis, y-axis, or origin.

Java Program :

import java.io.*;
class reflection
{
 static int x,y;
 static char m;
 static void main()throws IOException
 {
     input();
     cal();
    }
    static void input()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("A = (x,y)");
        System.out.print("\n\nx = ");
        x=Integer.parseInt(br.readLine());
        System.out.print("\ny = ");
        y=Integer.parseInt(br.readLine());
        System.out.print("\nReflection axis (x,y,o) : ");
        m=(char)br.read();
    }
    static void cal()
    {
        int c=0;
        if(m=='y' || m=='Y')
        x*=-1;
        else if(m=='x' || m=='X')
        y*=-1;
        else if(m=='o' || m=='O')
        {
            x*=-1;
            y*=-1;
        }
        else
        {
            System.out.print("\nInvalid input\n");
            c++;
        }
        if(c==0)
        display();
    }
    static void display()
    {
        System.out.print("\nThe reflected point A' = ("+x+","+y+")");
    }
}

Sunday 16 October 2011

To find non-fibonacci numbers

Question 62 : Write a program in Java to find and print the non-fibonacci numbers up to a limit entered by the user.

Java Program :

class non_fibonacci
{
 static void check(int n)
 {
    int a=2,b=3,i,j;
    System.out.print("The non-fibonacci numbers are : ");
    loop1: for(;;)
     {
         i=a+b;
         for(j=b+1;j<i;j++)
         {
             if(j>n)
            break loop1;
            System.out.print(j+" ");
        }
         a=b;
         b=i;
        }
    }
}

Friday 14 October 2011

Check Palindrome String

Question 61 : Write a program in Java to check whether a String is Palindrome or not.

Java Program :

import java.io.*;
class palindrome
{
     String s,s1;
      palindrome()
     {
         s="";
         s1="";
        }
        void Palin()throws IOException
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter the word : ");
            s=br.readLine();
            for(int i=s.length()-1;i>=0;i--)
            s1=s1+s.charAt(i);
            if(s1.equals(s))
            System.out.print("\nThe word '"+s+"' is palindrome");
            else
            System.out.print("\nThe word '"+s+"' is not palindrome");
        }
    }
     

Try Catch Exception

Demonstrating Try Catch Exception block.

Java Program :

class try_catch
{
 static void print()
 {
     double a;
     try
     {
         a=10/0;
     }
     catch(Exception e)
     {
         System.out.print("Error : "+e);
     }
    }
}

Tuesday 11 October 2011

Libraries 2 : Square root function

This program uses Newton's formula for calculating the square root of  a number taken as input from the user.

Java Program :

import java.io.*;
class sqrt_function
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int i;
     double a,b=2,c=0;
     System.out.print("Enter a number : ");
     a=Double.parseDouble(br.readLine());
     for(i=1;i<=10;i++)
     {
        c=(a/b);
        b=(c+b)/2;
     }
     System.out.print("\nSquare Root of "+a+" = "+b);  
    }
}

Sunday 9 October 2011

To convert a number into binary form

Question 60 : Write a program in Java to input a number from the user and convert it into binary notation.

Java Program :

class binary
{
 static void cal(int n)
 {
     int a,k=n;
     String s="";
     while(n>0)
     {
         a=n%2==0?0:1;
         s=String.valueOf(a)+s;
         n/=2;
        }
     System.out.print(k+" --> "+s);
    }
}

Friday 7 October 2011

Visitor's Request - 2

From judgingtime @ Yahoo Answers :

I'm writing a Java program that needs to utilize keyboard reader in a terminal I/O prompt so that the user inputs an integer, and the program checks to see if it is prime or composite. If the number is prime; the system also needs to print the prime factorization (for example, prime factors of 16 are 2, 2, 2, and 2.) If anyone can help me out here, it'd be greatly appreciated. I've hit a wall and it's getting late for me. Last and simply, I also need to put a (y/n) at the end to ask if you want to check another number, just so I don't have to re-run the program each and every time. I thank you in advance for any help!

Hello judgingtime, here's your program : 

Java Program :

import java.io.*;
class judgingtime
{
 static void check()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     char opt;
     int c,i;
     do
     {
        System.out.print("Enter a number : ");
       c=Integer.parseInt(br.readLine());
        if(prime(c)==true)
        System.out.print("\nThe number is prime !");
        else
        System.out.print("\nThe number is composite !");
        System.out.print("\n\nPrime Factors of "+c+" : ");
        for(i=1;i<=c;i++)
        {
            if(c%i==0 && prime(i)==true)
            {
                 System.out.print(i+" X ");
                 c=c/i;
                 i=1;
            }
            if(prime(c)==true)
            {
                System.out.print(c);
                break;
            }
        }
        System.out.print("\n\nDo you want to continue (Y/N) : ");
        opt=(br.readLine()).charAt(0);
        System.out.print("\n");
    }while(opt!='n' && opt!='N');
    System.out.print("Thank You");
}
    static boolean prime(int a)
    {
        int i,j=0;
        for(i=1;i<=a/2;i++)
        {
            if(a%i==0)
            j++;
        }
        if(j==1)
        return true;
        else
        return false;
    }
}
     

Prime factorization of a number

Question 59 : Write a program in Java to prime factorize a number taken as input from the user.

Java Program :

import java.io.*;
class prime_fact
{
 static void check()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     System.out.print("Enter a number : ");
     int c=Integer.parseInt(br.readLine());
     int i;
     System.out.print("\nPrime Factors of "+c+" : ");
     for(i=1;i<=c;i++)
     {
            if(c%i==0 && prime(i)==true)
            {
                 System.out.print(i+" X ");
                 c=c/i;
                 i=1;
            }
            if(prime(c)==true)
            {
                System.out.print(c);
                break;
            }
    }
}
    static boolean prime(int a)
    {
        int i,j=0;
        for(i=1;i<=a/2;i++)
        {
            if(a%i==0)
            j++;
        }
        if(j==1)
        return true;
        else
        return false;
    }
}
     

Wednesday 5 October 2011

To delete a value from an array

Question 58 : Write a program in Java to delete a value from an array.

Java Program :

class del
{
 int[] a;
 int n,p=-1;
 del(int[] arr,int num)
 {
     a=arr;
     n=num;
     search();
     del();
    }
    void search()
    {
        for(int i=0;i<a.length;i++)
        {
            if(a[i]==n)
            p=i;
        }
    }
    void del()
    {
        int b;
        if(p!=-1)
        {
            b=a[a.length-1];
            a[a.length-1]=a[p];
            a[p]=b;
            System.out.print("Array : { ");
            for(int i=0;i<a.length-1;i++)
            System.out.print(a[i]+" ");
            System.out.print("}");
        }
        else
        System.out.print("Error 404");
    }
}

To insert a value in an array

Question 57 : Write a program in Java to insert a value in an array.

Java Program :

class insert_val
{
 int[] a;
 int n,p;
 insert_val(int[] arr,int number,int position)
 {
     a=new int[arr.length+1];
     for(int i=0;i<arr.length;i++)
     a[i]=arr[i];
     n=number;
     p=position-1;
     check();
    }
    void check()
    {
        if(p>=0 && p<a.length)
        insert();
        else
        System.out.print("Array Index Out of Bounds Exception");
    }
    void insert()
    {
        a[a.length-1]=a[p];
        a[p]=n;
        System.out.print("Updated Array : ");
        array.display(a);
    }
}

Utilities 16 : Print in style

Compile and sit back to enjoy the surprise.

Java Program :

import java.io.*;
class print_smart
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int i,j;
     String s;
     System.out.print("Enter a string : ");
     s=br.readLine();
     s=s+"\n\nThank you";
     for(i=2;i<=s.length();i++)
     {
         try{Thread.sleep(300);}
         catch(InterruptedException e)
         {}
         System.out.print("\f"+s.substring(0,i));
        }
    }
}

To separate the digits of a number

Question 56 : Write a program in Java to separate the digits of a number taken as input from the user.

Java Program :

import java.io.*;
class separate
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int i;
     String a;
     System.out.print("Enter the number : ");
     a=br.readLine();
     System.out.print("\nThe digits are : ");
     for(i=0;i<=a.length()-1;i++)
     {
         System.out.print(a.charAt(i));
         if(i!=a.length()-1)
         System.out.print(" , ");
         else
         System.out.print(" .");
        }
    }
}
     

Tuesday 4 October 2011

Using continue

Here's a short program to demonstrate the use of the keyword "continue" in Java. It prints all the odd numbers up to n, as taken from the user.

Java Program :

class continue_
{
 static void cal(int n)
 {
     System.out.print("The odd numbers up to '"+n+"' are : ");
     for(int i=1;i<=n;i++)
     {
         if(i%2==0)
         continue;
         else
         System.out.print(i+" ");
        }
    }
}

Utilities 15 : Temperature converter

Yet another tool. This tool will help you to convert temperature values between Celsius, Kelvin, and Fahrenheit scales.

Java Program :

import java.io.*;
class temp_convert
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int opt;
     int t=1;
     double c;
     double i=0;
     double s=0;
     System.out.println("\t\t*****Welcome to temperature converter*****");
     while(t!=0)
     {
     System.out.println("\nPress 1 to convert degree celsius into degree fahrenheit");
     System.out.println("Press 2 to convert degree fahrenheit into degree celsius");
     System.out.println("Press 3 to convert degree celsius into kelvin temp.");
     System.out.println("Press 4 to convert degree fahrenheit into kelvin temp.");
     System.out.println("Press 5 to convert kelvin temp. into degree celsius");
     System.out.println("Press 6 to convert kelvin temp. into degree fahrenheit");
     System.out.print("\nEnter you choice : ");
     opt=Integer.parseInt(br.readLine());
     System.out.print("\n");
     switch(opt)
     {
         case 1:
         System.out.print("Enter degree celsius temp.(without the degree sign.) : ");
         c=Integer.parseInt(br.readLine());
         s=s+celsius(c);
         break;
         case 2:
         System.out.print("Enter degree fahrenheit temp.(without the degree sign.) : ");
         c=Integer.parseInt(br.readLine());
         s=s+fahr(c);
         break;
         case 3:
         System.out.print("Enter degree celsius temp.(without the degree sign.) : ");
         c=Integer.parseInt(br.readLine());
         s=s+kelvin(c);
         break;
         case 4:
         System.out.print("Enter degree fahrenheit temp.(without the degree sign.) : ");
         c=Integer.parseInt(br.readLine());
         i=i+fahr(c);
         s=s+kelvin(i);
         break;
         case 5:
         System.out.print("Enter kelvin temp. : ");
         c=Integer.parseInt(br.readLine());
         s=s+kc(c);
         break;
         case 6:
         System.out.print("Enter kelvin temp. : ");
         c=Integer.parseInt(br.readLine());
         i=i+kc(c);
         s=s+celsius(i);
         break;
         default:
         System.out.print("Invalid option\n");
        }
      if(opt==1)
      System.out.println("\nThe result is : "+s+" degree fahrenheit");
      if(opt==2)
      System.out.println("\nThe result is : "+s+" degree celsius");
      if(opt==3)
      System.out.println("\nThe result is : "+s+" kelvin");
      if(opt==4)
      System.out.println("\nThe result is : "+s+" kelvin");
      if(opt==5)
      System.out.println("\nThe result is : "+s+" degree celsius");
      if(opt==6)
      System.out.println("\nThe result is : "+s+" degree fahrenheit");
      if(opt!=1 && opt!=2 && opt!=3 && opt!=4 && opt!=5 && opt!=6)
      System.out.println("Please try again");
      s=0;
      i=0;
     System.out.println("\nEnter 1 to restart");
     System.out.println("Enter 0 to terminate the program");
     System.out.print("\nEnter yout choice : ");
     t=Integer.parseInt(br.readLine());
    }
        System.out.println("\nThank you for using this short program");
    }
    static double celsius(double d)
    {
        double w=0;
        w=((9*d)/5)+32;
        return w;
    }
    static double fahr(double e)
    {
        double x=0;
        x=((e-32)*5)/9;
        return x;
    }
    static double kelvin(double g)
    {
        double y=0;
        y=g+273;
        return y;
    }
    static double kc(double h)
    {
        double z=0;
        z=h-273;
        return z;
    }
}
       
       
       
         

To generate a sample matrix

Question 55 : Write a program in Java to generate a sample matrix based upon the number of rows and columns taken as input from the user.

Sample input : Rows = 2 ; Columns = 2

Sample output : 

[ 1 2 
  3 4 ]

Java Program :

import java.io.*;
class matrix
{
 int[] a;
 static int opt=0;
 static void main()throws IOException
 {
     order();
    }
    static void order()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        if(opt==0)
        {
            System.out.print("Enter number of rows : ");
            int r=Integer.parseInt(br.readLine());
            System.out.print("\nEnter number of columns : ");
            int c=Integer.parseInt(br.readLine());
            System.out.print("\n=> Order of matrix : "+r+" X "+c);
            System.out.print("\n\nSample matrix : \n\n");
            System.out.print("[ ");
            int c1=0;
            for(int i=1;i<=(r*c);i++)
            {
                if(c1==c)
                {
                    System.out.print("\n  ");
                    c1=0;
                }
                c1++;
                System.out.print(i+" ");
            }
            System.out.print("]");
        }
    }
}
        

Monday 3 October 2011

Celebrations


CENT POSTS AT LAST
Thank you all, for your vital contributions to this blog.
This was impossible without you all.

HAPPY CENTURY TO ICSE JAVA

Utilities 14 : Percentage change

This tool will help you to calculate the increment/decrements and increased/decreased value, while increasing or decreasing a value by a constant percentage.

Java Program :

import java.io.*;
class percent_change
{
   static double n;
   static double p,c;
  static void main()throws IOException
  {
      BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Enter the number : ");
      n=Integer.parseInt(b.readLine());
      System.out.print("\nEnter percentage (w/o % sign) : ");
      p=(Double.parseDouble(b.readLine())*n)/100;
      System.out.print("\nSelect mode : Enter 'i' to increment or 'd' to decrement : ");
      String o=b.readLine();
      switch((int)o.charAt(0))
      {
          case 105:
          case 73:
          increment();
          break;
          case 100:
          case 68:
          decrement();
          break;
          default:
          System.out.print("\nWrong input\n\n");
          main();
        }
        display();
    }
    static void increment()
    {
        n=n+p;
        c=0;
    }
     static void decrement()
    {
        n=n-p;
        c=1;
    }
    static void display()
    {
        System.out.print("\n");
        if(c==0)
        System.out.print("The incremented value is : "+n+"\n\nChange : + ");
        if(c==1)
        System.out.print("The decremented value is : "+n+"\n\nChange : - ");
        System.out.print(p);
    }
}

Utilities 13 : Sentence diagnostics

This program will help you to break a sentence into it's constituent words and find out the number of vowels and consonants in each.

Java Program :

import java.io.*;
class vowels
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int i,j,b=0,v=0,c=0,space=0;
     char k,d='a';
     String a,s="";
     System.out.print("Enter the sentence : ");
     a=br.readLine();
     System.out.print("\n");
     for(i=0;i<=a.length()-1;i++)
     {
         k=a.charAt(i);
         if(k==' ')
         {
              check(i-1,b,a);
              b=i+1;
            }
         if(k!=' ')
         space=space+1;
        }
        if(space!=a.length())
        check(a.length()-1,b,a);
        if(space==a.length())
        check(a.length()-1,0,a);
        System.out.println("Thank you for using this short program");
        }
        static void check(int z,int y,String x)
        {
            int j,v=0,c=0;
            char d;
            String s="";
            for(j=y;j<=z;j++)
            {
                 d=x.charAt(j);
                 s=s+d;
                 if(d=='a' || d=='A' || d=='e' || d=='E' || d=='i' || d=='I' || d=='o' || d== 'O' || d=='u' || d=='U')
                 v=v+1;
                 else
                 c=c+1;
              }
              System.out.println(s+" = No. of vowels = "+v+" & No. of consonants = "+c);
              System.out.print("\n");
    }
}
       
             
             
       
     

Toggle case

Question 54 : Write a program in Java to toggle the case of a string taken as input from the user.

Sample input : JavA

Sample output : jAVa

Java Program :

import java.io.*;
class toggle_case
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int i,s,k=0;
     String a;
     System.out.print("Enter a string : ");
     a=br.readLine();
     System.out.print("\nToggled cases are : ");
     for(i=0;i<=a.length()-1;i++)
     {
         s=(int)a.charAt(i);
         if(s!=' ')
         {
             if(s>=65 && s<=90)
             k=s+32;
             if(s>=97 && s<=122)
             k=s-32;
             System.out.print((char)k);
            }
            else
            System.out.print(" ");
        }
        System.out.print("\n");
        System.out.println("\nThank you for using this short program");
    }
}

     

Utilities 12 : Name initials

This program will help you to print the initials of a name taken as input from the user.

Java Program :

import java.io.*;
class name_initials
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int i,d=0,space=0;
     char k;
     String a;
     System.out.print("Enter the name : ");
     a=br.readLine();
     System.out.print("\nName initials : ");
     for(i=0;i<a.length();i++)
     {
         k=a.charAt(i);
         if(k==' ')
         {
             space=i+1;
             System.out.print(a.charAt(d)+".");
             d=i+1;
            }
        }
            for(i=space;i<a.length();i++)
            {
                k=a.charAt(i);
                System.out.print(k);
            }
            System.out.print("\n");
            System.out.println("\nThank you for using this short program");
       
    }
}
               
       
             

To find the distance between two points

Question 53 : Write a program in Java to find and print the distance between two point whose X and Y - axis coordinates have been taken as input from the user.

Java Program :

import java.io.*;
class point_distance
{
  static int x,x1,y,y1;
  static double d;
  static void input()throws IOException
  {
      BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
      System.out.print("For point A : ");
      System.out.print("\n\nEnter abcisssa (x-co-ordinate) : ");
      x=Integer.parseInt(b.readLine());
      System.out.print("\nEnter ordinate (y-co-ordinate) : ");
      y=Integer.parseInt(b.readLine());
      System.out.print("\nFor point B : ");
      System.out.print("\n\nEnter abcisssa (x-co-ordinate) : ");
      x1=Integer.parseInt(b.readLine());
      System.out.print("\nEnter ordinate (y-co-ordinate) : ");
      y1=Integer.parseInt(b.readLine());
      cal();
      display();
    }
    static void cal()
    {
        d=Math.sqrt(((x-x1)*(x-x1))+((y-y1)*(y-y1)));
    }
    static void display()
    {
        System.out.print("\nDistance between A ("+x+","+y+") and B ("+x1+","+y1+") : "+d+" units");
    }
}
      

Sunday 2 October 2011

Libraries 1 : String length function

Here's a program that mimics the string length function.

Java Program : 

class str
{
 static int len(String s)
 {
     int i,length=0;
     char c;
     for(i=0;;i++)
     {
         try
         {
            c=s.charAt(i);
            length++;
        }
        catch(Exception e)
        {
            break;
            }
        }
     return length;
}
}

Call this class wherever required, syntax will be like this :

Syntax : 

int length=str.len(string_name);

Utilities 11 : Leap year

Here's another great tool for checking whether a particular year was / is / will be a leap year or not. Just copy and compile it.

Java Program :

import java.io.*;
class leap
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int y,s=0;
     System.out.print("Enter an year number : ");
     y=Integer.parseInt(br.readLine());
     s=y%100;
     if(s==0)
     {
        if(y%400==0)
        System.out.print("\nThe year was / is / will be a leap year");
        else
        System.out.print("\nThe year was / is / will not be a leap year");
    }
    else
    {
        if(y%4==0)
        System.out.print("\nThe year was / is / will be a leap year");  
        else
        System.out.print("\nThe year was / is / will not be a leap year");
    }
    }
}

Utilities 10 : Approximate

Hope you are all enjoying Durga Puja 2011. Here's a quick tool that will approximate any decimal value to two decimal places.

Java Program :

import java.io.*;
class approximation
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String a,b="",e="";
     int i,c=0,d=0;
     double input,app=0,num=0;
     char k;
     System.out.print("Enter the number : ");
     input=Double.parseDouble(br.readLine());
     a=Double.toString(input);
     for(i=0;i<=a.length()-1;i++)
     {
         k=a.charAt(i);
         if(k=='.')
         {
         c=i+1;
         d=i-1;
        }
        }
        for(i=c;i<=c+2;i++)
        b=b+a.charAt(i);
        for(i=0;i<=d;i++)
        e=e+a.charAt(i);
        app=Integer.parseInt(e);
        num=Integer.parseInt(b);
        if(num%10>=5)
        {
        num=num-(num%10);
        num=num+10;
        }
        else
        num=num-(num%10);
        num=num/1000;
        app=app+num;
        System.out.print("\nThe approx. value is : "+app);
    }
}
         
         
       
   

To find the factorial of a given number

Question 52 : Write a program in Java to find and print the factorial of a number.

Factorial : Let number be 5

= 5 * 4 * 3 * 2 * 1 = 120

Java Program :

import java.io.*;
class factorial
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int n,i;
     System.out.print("Enter the number : ");
     n=Integer.parseInt(br.readLine());
     int s=n;
     for(i=n-1;i>=1;i--)
     {
         s=s*i;
        }
        System.out.print("\n");
        System.out.println("The result = "+s);
    }
}

To find the second highest number

Question 51 : Write a program in Java to find the second highest number from a list of numbers taken as input from the user (w/o using array). The list terminates when the user enters 0.

Java Program :

import java.io.*;
class sec_high
{
 static void high()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int max=0,sec=0,n=0,i,last=0;
     System.out.print("Enter the numbers one by one and 0 to exit");
     System.out.print("Enter number : ");
     max=Integer.parseInt(br.readLine());
     System.out.print("\nEnter number : ");
     sec=Integer.parseInt(br.readLine());
     if(sec>max)
    {
     last=sec;
     sec=max;
     max=last;
    }
   do
   {
         System.out.print("\nEnter number : ");
         i=Integer.parseInt(br.readLine());
         if(i!=0)
         n=i;
         if(n<max && n<sec)
         continue;
         else if(n>max)
         {
             sec=max;
             max=n;
            }
            else if(n<max && n>sec)
            sec=n;
        }while(i!=0);
        System.out.print("\nHighest number : "+max);
        System.out.print("\n\nSecond highest number : "+sec);
    }
}

Mahatma Gandhi Jayanti | Gandhiji Quotes

Mohandas Karamchand Gandhi
Let us all pay tribute to our hero, Gandhi ji , on this very auspicious occasion of Mahatma Gandhi Jayanti.

Mohandas Karamchand Gandhi (2 October 1869 – 30 January 1948) was the pre-eminent political and ideological leader of India during the Indian independence movementA pioneer of satyagraha, or resistance to tyranny through mass civil disobedience — a philosophy firmly founded upon ahimsa, or total nonviolence — Gandhi led India to independance and inspired movements for civil rights and freedom across the world. We owe him our country's freedom.


Quotes : 

A coward is incapable of exhibiting love; it is the prerogative of the brave.

A man is but the product of his thoughts what he thinks, he becomes. 

A man who was completely innocent, offered himself as a sacrifice for the good of others, including his enemies, and became the ransom of the world. It was a perfect act. 

A policy is a temporary creed liable to be changed, but while it holds good it has got to be pursued with apostolic zeal. 

A weak man is just by accident. A strong but non-violent man is unjust by accident. 

All the religions of the world, while they may differ in other respects, unitedly proclaim that nothing lives in this world but Truth. 

Always aim at complete harmony of thought and word and deed. Always aim at purifying your thoughts and everything will be well.

Among the many misdeeds of the British rule in India, history will look upon the act depriving a whole nation of arms as the blackest. 

An error does not become truth by reason of multiplied propagation, nor does truth become error because nobody sees it. 

Saturday 1 October 2011

Input Streams in Java

Take a look at these two programs to understand the usage and syntax of these input methods in Java.

1) Using Buffered Reader : 

Java Program : 

import java.io.*;
class input_string
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String a;
     System.out.print("Enter a string : ");
     a=br.readLine();
     System.out.print("You entered : ");
     System.out.print(a+" "+a);
 }
}

2) Using Scanner : 

Java Program : 

import java.util.Scanner;
class scanner
{
 static void main()
 {
     Scanner scan=new Scanner(System.in);
     System.out.print("Enter anything : ");
     String k=scan.nextLine();
     System.out.print("\nYou have entered : "+k);
    }
}

3) Bonus : 

Special case while taking a character input : 

Java Program : 

import java.io.*;
import java.lang.*;
class input_char
{
 public void input()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     char a;
     System.out.print("Enter a character : ");
     a=(char)System.in.read();
     System.out.print("\nYou entered : "+a);
  }
}

Other than this, you can even take a String input and find out its first character using charAt(0).

For example : 

\\Rest part is omitted
String s="hello world";
char k=s.charAt(0);
System.out.print("First letter : "+k);

Output : 

First letter : h



To print the given pattern

Question 50 : Write a program in Java to print the given pattern.

123454321
123      321
12          21
1              1

Java Program : 

class pattern_35
{
 static void cal()
 {
     int i,j,k,c=0,a=7;
     for(i=5;i>=1;i--)
     {
         for(j=1;j<=i-1;j++)
         System.out.print(j);
         if(c==0)
         System.out.print(5);
         else
         {
            for(k=7;k>=a;k--)
             System.out.print(" ");
            }
         for(j=i-1;j>=1;j--)
         System.out.print(j);
         System.out.print("\n");
         c++;
         a=a-2;
        }
    }
}
         

To reverse any integer ( number )

Question 49 : Write a program in Java to reverse any integer ( with any number of digits ) taken as input by the user.

Sample input : 12345

Sample output : 54321

Java Program : 

class rev
{
 static void cal(int n)
 {
     int rev=0;
     while(n>0)
     {
         rev=(rev*10)+(n%10);
         n=n/10;
        }
        System.out.print("The reversed number : "+rev);
    }
}

To reverse a String

Question 48 : Write a program inn Java to reverse a String taken as input in Java.

Sample input : JAVA

Sample output : AVAJ

Java Program : 

class string_rev
{
 static void reverse(String s)
 {
     String rev="";
     int i;
     for(i=s.length()-1;i>=0;i--)
     rev=rev+s.charAt(i);
     System.out.print("String input : "+s);
     System.out.print("\n\nReversed string : "+rev);
    }
}

To print and find the sum of the fibonacci series

Question 47 : Fibonacci series = 0,1,1,2,3,5,8,13.......,n

Print and find the sum of the series.

Java Program :

public class fibonacci_series
{
 public static void main(int n)
 {
     int a=0;
     int b=1;
     int s=0;
     int c=0;
     int i;
     s=s+a+b;
     System.out.print("The fibonacci series = "+a+","+b+",");
     for(i=3;i<=n;i++)
     {
         c=a+b;
         System.out.print(c+",");        
         a=b;
         b=c;
         s=s+c;
        }
        System.out.println("upto "+n+" terms completed");
        System.out.println("\nThe sum of the fibonacci series upto "+n+" terms = "+s);
    }
}
       

To print and find the sum of a given series

Question 46 : S = 1 + 12 + 123 + 1234 + ..... + n terms.

Print and find sum of the series.

Java Program : 

class series_2
{
 int n,sum=1;
 series_2(int a)
 {
     n=a;
     cal();
    }
    void cal()
    {
        int s=1;
        System.out.print("The series : 1+");
        for(int i=2;i<=n;i++)
        {
            s=(s*10)+i;
            sum=sum+s;
            if(i==n)
            {
                System.out.print(s);
                break;
            }
            System.out.print(s+"+");
        }
        System.out.print("\nSum of the series : "+sum);
    }
}

Utilities 9 - Stylish way of array input

Just copy the following program.

Java Program :

import java.io.*;
class array_input
{
 static void input()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int[] dump,ret;
     String s,s1="";
     char k;
     int c=0,ac=0;
     System.out.print("Enter the array : ");
     s=br.readLine();
     dump=new int[s.length()];
     while(c<s.length())
     {
            while(c<s.length())
            {
                k=s.charAt(c);
                c+=1;
                if((int)k>=48 && (int)k<=57)
                {
                    s1=s1+k;
                    continue;
                }
                break;
            }
            if(s1!="")
            {
                dump[ac]=Integer.parseInt(s1);
                ac+=1;
            }
            s1="";
        }
     ret=new int[ac];
     System.arraycopy(dump,0,ret,0,ac);
     System.out.print("\nNumbers are : ");
     for(int i=0;i<ret.length;i++)
     System.out.print(ret[i]+"  ");
    }
}

To give the input, write the integers with spaces or commas or any String between it, and hit enter. You'll see the individual integers popping up. Paste this code wherever you want, and just corp the array "ret" into anywhere.

ShareThis