Thursday, December 26, 2013

Addition of numbers each number has more than 1000 digits in java

//Author ramraj.vasavi
package com.rrv;
import java.util.Scanner;
class Add
{
    public static void main(String[] args)
    {
        Scanner scannerInput=new Scanner(System.in);
        System.out.println("Enter your First Number");
        String first=scannerInput.next();
        System.out.println("Enter your Second Number");
        String second=scannerInput.next();
        int[] num1=convertInt(first);
        int[] num2=convertInt(second);
        int fLength=num1.length;
        int sLength=num2.length;
        if(first.equals("0")&&second.equals("0"))
        {
         System.out.println("Addition of two Numbers is: "+"0");
        }
        else if(first.equals("0"))
        {
            
          System.out.println("Addition of two Numbers is: "+second);
        }
        else if(second.equals("0"))
        {
          System.out.println("Addition of two Numbers is: "+first);
        }
        else{
           if(fLength>sLength)
             Add.add(num1,num2);
           else
             Add.add(num2,num1);
        } 
        
    }
    public static void add(int[] oparend1,int[] oparend2)
    {
        int[] result=new int[oparend1.length];
        int op2Length=oparend2.length-1;
        int op1Length=oparend1.length-1;
        int sum=0;
        for(int index=0;index<=op1Length;index++)
        {
            if(index>=oparend2.length)
             sum=oparend1[op1Length-index]+sum;
            else
                 sum+=oparend1[op1Length-index]+oparend2[op2Length-index];
        int digit=sum%10;        
         sum=sum/10;
         result[index]=digit;
        }
        String output="";
        for(int index=result.length-1;index>=0;index--)
        {
                        output=output+result[index];
         }
        System.out.println("Addition of two numbers is: "+output);
    }
   public static int[] convertInt(String str){
       int[] arr=new int[str.length()];
      for(int index=0;index<str.length();index++)
       {
           arr[index]=(int)str.charAt(index)-48;
       }
     return arr;
   }
}

Output of Addition.java:

Enter your First number: 54832415789132118

Enter your Second Number: 9213849898

Addition of Two numbers is: 54832425002982016

How many ways to swap to numbers without using third variable in java

Swapping of two numbers program is a frequently asking question in interviews.If we want to swap to two numbers ,We will use third variable. Let's see simple example below

public static void swappingNumbers(num1, num2) {
        var tempVariable = num1;
        num1 = num2;
        num2 = tempVariable;
}

Like above we will do. But we can do this program in three ways without using third variable.

1) In first way, we add first and second numbers then store result into first variable. After subtract second value from first result, store that result into second variable.At last, subtract second result from first result then store this result into first variable.For more clarification see  below program

    public static void swappingNumType1(num1, num2)
     {
          num1 = num1 + num2;
          num2 = num1 - num2;
          num1 = num1 - num2;
          System.out.println("num1 = "+num1+"  num2 = "+num2);
     }
    
2)
              In second way,we multiply first and second numbers then store this  result into first variable. After devide first result with second value,store second result into second variable. At last, divide first result with second result then store result into first variable. For more clarification see below program

     public static void swappingNumType1(num1, num2)
     {
          num1 = num1 * num2;
          num2 = num1 / num2;
          num1 = num1 / num2;
          System.out.println("num1 = "+num1+"  num2 = "+num2);
     }

3) In third way,we  will add two numbers by using ^(XOR) operator.

     public static void swappingNumType1(num1, num2)

     {
          num1 = num1 ^ num2;
          num2 = num1 ^ num2;
          num1 = num1 ^ num2;
          System.out.println("num1 = "+num1+"  num2 = "+num2);
     }

We will also swap two Strings without using third variable. It is possible by using subString() method of String API.

     public static void main(String[] args)
{
String a = "rrv";
String b = "techdiamod";
a = a+b;
b=a.substring(0,a.length()-b.length());
a=a.substring(b.length());
System.out.println("Swappng Strings are "+a+"    "+b);

    }


         
  

Display Stars using javascript

a. Take a positive integer value from the respondent as below fig. and Display Star Diamond.
b. Validate above form field
c. ON VALIDATION DISPLAY PROPER USER FRIENDLY MESSAGE TO USER.
d. Try to design a good looking html page with proper alignment..
e. You are only allowed to use HTML for design the page and JavaScript for scripting logic.



<html>
<head>
<script type="text/javascript">
function display(){
var reg=/^[0-9]$/;
var content = document.getElementById("top").innerHTML;
var divText="<br><fieldset style='background-color:green;color: #123abc;width: 400px;'><legend>"+"Star Diamond"+"</legend><fieldset style='background-color:yellow;color: #123546;width: 75px;'>";
var input=document.getElementById("tex").value*1;
var space=input-2;
var line=(input+1)/2;
;
if(input==""){
alert("Please enter Number");
return false;
}
if((input%2)==0)
{
alert("Please enter Number");
return false;
}
for(var i=0; i<line;i++)
{
for (var c = 1 ; c < space; c++ )
divText=divText+"&nbsp";
space--;
for (var d = 1 ; d <=2*i+1 ; d++ )
divText=divText+"*";
divText=divText+"<br>";
}
var down=(input-1)/2;
var spa=1;
for(var r=down; r>0; r--)
{
for(var sp=spa; sp>=1; sp--)
divText=divText+"&nbsp";
spa++;
for(var m=1; m<=2*r-1; m++)
divText=divText+"*";
divText=divText+"<br>";
}
divText=divText+"</fieldset>";
content=content+divText;
document.getElementById("top").innerHTML=content;
return true;
}
</script>
</head>
<body><center><form id="1">
<div id="top">
<fieldset style="background-color:orange;color: #123abc; width: 400px;">
<legend style="background-color:green;color: #ff0000; font-family: verdana; font-size: 14pt;">DISPLAY</legend>
<div>Enter Number you want:<input type="textid="texvalue=""><input type="buttonid="disvalue="Displayonclick="return display()"></div>
</fieldset>
</div>
</form></center>
</body>
</html>

Pan Digit Number program

/** Program Name PanDigit.java
     Author :RamRajVasavi

*/
package blog.rrvTechDiamond;
import java.util.Scanner;
public class PanDigit {
             //Writing codefor main() method
public static void main(String[] args) {
//creating object for Scanner Class
Scanner scannerInput=new Scanner(System.in);
                          //Printing Message
System.out.println("Enter No of Digit PanNumber want");
                           //Taking input from endUser
int noOfDigits=scannerInput.nextInt();
                          //Declaring variables
                          boolean check=true;
int panIndex;
int endNo=1;
int index=1;
int integer=10;
int panIf=0;
//creating start and end range
while(index<=noOfDigits)
{
endNo=endNo*integer;
index++;
}
int limit=endNo-1;
int startNo=(endNo/10)+1;
endNo=endNo-(endNo/10)*(10-(noOfDigits+1));
panIndex=startNo;
                          //checking the number is panDigit or not
while(panIndex<=endNo){
                                        //calling panNumber() method
check=panNumber(panIndex,noOfDigits);
if(check==true){
panIf++;
System.out.println(panIndex+" is PanDigit Number");
}
else{
    System.out.println(panIndex+" is not PanDigit Number");
}
panIndex++;
}
System.out.println("The PanDigitNumber from "+startNo+"---"+limit+" is: "+panIf);
}
             //Writing code for panNumber()method 
public static boolean panNumber(int panIndex,int noOfDigits){
                          //creating array object
int arr[]=new int[noOfDigits];
int index=-1;
                          //Number is convert to array
while(panIndex>0){
index++;
int digit=panIndex%10;
arr[index]=digit;
panIndex=panIndex/10;
}
                          //checking for duplicate numbers
for(int digitIndex=0;digitIndex<noOfDigits;digitIndex++){
for(int lowIndex=0;lowIndex<noOfDigits;lowIndex++){
if((digitIndex!=lowIndex)&&(arr[digitIndex]==arr[lowIndex]))
return false;
if(arr[digitIndex]==0)
return false;
}
}
int count=0;
                          //Number contains digits less than that noOfDigits we entered
for(int idex=0;idex<noOfDigits;idex++){
if(arr[idex]<=noOfDigits)
count++;
}
if(count==noOfDigits)
return true;
return false;
}

}


Output:

D:\>java PanDigit
Enter No of Digit PanNumber want
5

10001 is not PanDigit Number
10002 is not PanDigit Number
10003 is not PanDigit Number
10004 is not PanDigit Number
10005 is not PanDigit Number
10006 is not PanDigit Number
10007 is not PanDigit Number
10008 is not PanDigit Number
10009 is not PanDigit Number
10010 is not PanDigit Number
10011 is not PanDigit Number
10012 is not PanDigit Number
10013 is not PanDigit Number
----
----
----
----
----

ButterFly program

package com.rrv;

import java.util.Scanner;


public class ButterFlyLogic {

public static void main(String[] args)
 {
Scanner scannerInput=new Scanner(System.in);
   //take input from user
  System.out.println("Enter Number of Steps you want: ");
int numOfSteps=scannerInput.nextInt();
  //spaceDecre variable for printing spaces
int spaceDecre=numOfSteps*2-3;
  //stepIncre variable for printing step wise
int stepIncre=1;
  //for printing top of the rows
for(int i=numOfSteps;i>1;i--)
{
   //call method steps()
ButterFlyLogic.steps(stepIncre,spaceDecre,i);
 spaceDecre=spaceDecre-2;
stepIncre++;
}
int ones=numOfSteps*2-1;
for(int i=0;i<ones;i++)
{
System.out.print("1");
}
System.out.println("\n");
  //stepIncre and spaceDecre variable for bottom steps
stepIncre=numOfSteps-1;
spaceDecre=1;
  //for printing below steps
for(int j=2;j<=numOfSteps;j++)
{
  //call method steps()
ButterFlyLogic.steps(stepIncre, spaceDecre, j);
spaceDecre=spaceDecre+2;
stepIncre--;
  }
}
  //method for printing steps
public static void steps(int stepIncre,int spaceDecre,int i)
{
int step=stepIncre;
 //printing leftside values
while(step>0)
{
System.out.print(i);
step--;
}
int space=spaceDecre;
  //printing spaces
while(space>0)
{
System.out.print(" ");
space--;
}
step=stepIncre;
  //printing rightside values
while(step>0)
{
System.out.print(i);
step--;
}
System.out.println("\n");

}

}


OUTPUT:

Enter Number of Step you want:
5


5            5
44         44
333     333
2222  2222
111111111
2222  2222
333     333
44         44
5            5

Monday, December 9, 2013

Find the String length without using the String API of Java

                                   Generally, String is collection of Characters.String are immutable objects in Java. String is playing vital role in Java programming language. Java main() method parameter is also String array and Java is taking defaultly String. If we want to know the length of the String in java by using String API method length().But my question is how to find the length of the String without using String API of Java. Is it possible to find the String length without String API? Yes,it is possible to find String length without String API.

                                  By using File concept we can find the length of the String. By storing the each character of the String into the file and parallelly counting the characters. See the below example

package com.rrvtechdiamond;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class LengthOfString {

public static void main(String[] args) throws IOException {

          String nameOfBlog = "RRV TECH DIAMOND";
          
 File file = new File("G:/rrvtechdiamond.txt");//creating file object
 
 file.createNewFile();// creating file 
 
 
 FileWriter fileWriter = new FileWriter(file);
 
 fileWriter.write(nameOfBlog);//By using the write method write String to file
 
 fileWriter.close();//close the file
 
 FileReader fileReader = new FileReader(file);//create FileReader object
          
 int characterValue = 0, count = 0;
 
 while((characterValue = fileReader.read()) != -1){
 count++;
 }
 fileReader.close();//close fileReader
 
 System.out.println("length of the String is: "+count);
 
 
}

Output :

length of the String is: 16

Monday, December 2, 2013

Rename the name of the file with current system date by using java program

                      File is using to store the data permanently on disk in computer. We give names to individual files. Creating file, saving the file and renaming the file on GUI system very easy but programmatically we write some code and today our topic is this one. See the below program for the answer.   


import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DateAsFileName {
public static void main(String[] args) throws IOException {
         // create file object
         File file=new File("G:/text.txt");
         //create DateFormat object 
        file.createNewFile();
         
         //create calendar class object
         Calendar calendar = Calendar.getInstance();
         Date ss = calendar.getTime();
         int day = calendar.get(calendar.DAY_OF_MONTH); 
         int month = calendar.get(calendar.MONTH);
         int year = calendar.get(calendar.YEAR);
         String s="G:/"+day+"-"+month+"-"+year+".txt";
        file.renameTo(new File(s));
}

}