Friday, April 5

Generating & finding the given number is Prime Numbers or not in Java

Hi All,

A number is called as a prime if it has only two divisors. In other words, a number which is divided only by 1 and itself. i.e.; number of factors for a prime number should only be 5 (1 and itself).

Here I tried to get the number of prime numbers below a given number. and given number is prime number  or not .

import java.util.Scanner;

public class primeno {

    public static void main(String[] args) {

        System.out.println("Please enter the number: ");
        int limit = new Scanner(System.in).nextInt();
        System.out.println("Generate Prime numbers between 1 and " + limit);
        // loop through the numbers one by one
        for (int i = 1; i < limit; i++) {
            boolean isPrimeNumber = true;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }
            // print the number if prime
            if (isPrimeNumber) {
                System.out.print(i + " ");
            }
        }
        System.out.println("\n\nFinding given number is prime number or not: ");
        if (finprime(limit)) {
            System.out.println("The given number is a prime number :-) " + limit);
        } else {
            System.out.println("The given number is not a prime number :-( " + limit);
        }
    }

    public static boolean finprime(int x) {
        int i;
        for (i = 2; i < x; i++) {
            if (x % i == 0) {
                break;
            }
        }
        if (i == x) {
            return true;
        }
        return false;
    }
}


out put:

~~~~~~


Please enter the number:
50
Generate Prime numbers between 1 and 50
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Finding given number is prime number or not:
The given number is not a prime number :-( 50

Finding GCD & LCD for given two numbers in java

Hi All,



The greatest common divisor (gcd), also known as the greatest common factor (gcf), or highest common factor (hcf).of two or more integers (at least one of which is not zero), is the largest positive integer that divides the numbers without a remainder.

The least common multiple  is the smallest positive integer that is a multiple of both the numbers.

import java.util.Scanner;

//main class
public class GCD_LCD {

    private static int lcm;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number1: ");
        int num1 = input.nextInt();
        System.out.print("Enter the number2: ");
        int num2 = input.nextInt();
        // for GCD
        if (num1 > num2) {
            System.out.println("the GCD of " + num1 + " and " + num2 + " is " + GCD(num1, num2));
        } else {
            System.out.println("the GCD of " + num1 + " and " + num2 + " is " + GCD(num1, num2));
        }

        //For LCD
        LCD(num1, num2);
    }

    public static int GCD(int x, int y) {
        int result;
        if (y == 0) {
            return x;
        }
        result = GCD(y, x % y);
        return result;
    }

    public static int LCD(int x, int y) {
        for (int i = 1; i <= x * y; i++) {
            if (i % x == 0 && i % y == 0) {
                lcm = i;
                break;
            }
        }
        System.out.println("the LCD of " + x + " and " + y + " is " + lcm);
        return 0;

    }
}

output:

~~~~~


Enter the number1: 30
Enter the number2: 72
the GCD of 30 and 72 is 6
the LCD of 30 and 72 is 360

Fibonacci series for given number in Java

Hi All,

Java program to find Fibonacci series of a given number



import java.io.*;
import java.util.*;

public class fibonacci {
public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter value of n: ");
    String st = reader.readLine();
    int num = Integer.parseInt(st);
    int f1=0,f2=0,f3=1;
    for(int i=1;i<=num;i++){
        System.out.println(f3);
        f1=f2;
        f2=f3;
        f3=f1+f2;
    }
}
}


Output:

~~~~~~

Enter value of n: 5
1
1
2
3
5

 

 


Thursday, April 4

Summation of a given set of Numbers using java (calculate given sum of digits in java)

Hi All,

 Summation of a set of Numbers, It used to calculate the sum of digits of given numbers :)


import java.io.*;

public class Summation {

    public static void main(String arg[]) {
        try {
            BufferedReader din = new BufferedReader(new InputStreamReader(System.in));
            int num, rem, sum;
            System.out.println(" Summation of a set of Numbers ");
           
            System.out.println("Please enter the number the sum of a digit: ");
            num = Integer.parseInt(din.readLine());
            rem = 0;
            sum = 0;

            while (num > 0) {
                rem = num % 10;  //getting remainder value stored in rem variable
                sum = sum + rem; // adding rem values to sum
                num = num / 10; // divide the number by 10 get remove the remainder value
            }

            System.out.println("The total Summation of the digit is : " + sum);
        } catch (IOException e) {
            System.out.println("Wrong Input");
        }
    }
}


output:


 Summation of a set of Numbers
Please enter the number the sum of a digit:
12121
The total Summation of the digit is :7

Factorial number calculation using java with Recursion method and Non-Recursion method

Hi All,


I tried Factorial number calculation using java with Recursion method and non-Recursion method :-)

import java.io.*;

public class factorial {

 public static void main(String[] args) throws IOException {
        // Using Non Recursion method
 
            BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the number");
            int a = Integer.parseInt(object.readLine());
            int fact = 1;
            System.out.println("Using Non Recursion method");
            System.out.println("Factorial of " + a + ":");
            for (int i = 1; i <= a; i++) {
                System.out.print(i + "*");
                fact = fact * i;
            }
            System.out.println(" = "+fact);
   
         // Using Recursion method
      
        int num = new factorial().RecursionFactorial(a);
        System.out.println("Using Recursion method " +num);
    }

    public int RecursionFactorial(int num) {

        int returnValue;

        if (num == 1) {
            return 1;
        }

        returnValue = RecursionFactorial(num - 1) * num;

        return returnValue;

    }
}


output:

Enter the number
8
Using Non Recursion method
Factorial of 8:
1*2*3*4*5*6*7*8* = 40320
Using Recursion method 40320

 

 

 



Wednesday, April 3

Swaping two numbers using temporary variable also without temporary variable in java

Hi All, 


Here I am tried swap two numbers using temporary variable also without temporary variable :)



public class swapTwoNos {
   
    public static void main(String[] args){
       
        // Using temporary variable for swapping two numbers        
        int var1=50;
        int var2=100;
        System.out.println("Using temporary variable for swapping two numbers");
        System.out.println("");
        System.out.println(" Before swapping numbers  \n var1 :"+var1+" var2 :"+var2);
        swap(var1,var2); // calling swap function for exchage the values
        withoutTemp(var1,var2);
    }

    private static void swap(int var1, int var2) {
       int temp =var1;
       var1=var2;
       var2=temp;
       System.out.println("After swapping numbers with temporary variable \n var1 :"+var1+" var2 :"+var2);      
    }

    private static void withoutTemp(int var1, int var2) {
      System.out.println("Using temporary variable for swapping two numbers"); 
      System.out.println("");
       var1 = var1 + var2;
       var2 = var1 - var2;
       var1 = var1 - var2;
       System.out.println("After swapping numbers without temporary variable \n var1 :"+var1+" var2 :"+var2);
    }   
   
}


output:

Using temporary variable for swapping two numbers

 Before swapping numbers 
 var1 :1 var2 :2
After swapping numbers with temporary variable
 var1 :2 var2 :1




Using without temporary variable for swapping two numbers

 After swapping numbers without temporary variable
 var1 :2 var2 :1



Write a Xml File using Java Program in directory also console

Hi All,


Here I try to write a simple XML file using java code.



import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class xmlWrite {

    public static void main(String argv[]) {

      try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // create root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Department");
        doc.appendChild(rootElement);

        // create  a employee elements
        Element Empl = doc.createElement("Employee");
        rootElement.appendChild(Empl);

        // set attribute to employee element
        Attr attr = doc.createAttribute("id");
        attr.setValue("1");
        Empl.setAttributeNode(attr);
       

        // firstname elements of employee
        Element fname = doc.createElement("FirtName");
        fname.appendChild(doc.createTextNode("Skitech"));
        Empl.appendChild(fname);

        // lastname elements of employee
        Element lname = doc.createElement("LastName");
        lname.appendChild(doc.createTextNode("krish"));
        Empl.appendChild(lname);

        // nickname elements of employee
        Element pname = doc.createElement("NickName");
        pname.appendChild(doc.createTextNode("bala"));
        Empl.appendChild(pname);

        // salary elements of employee
        Element sal = doc.createElement("salary");
        sal.appendChild(doc.createTextNode("200000"));
        Empl.appendChild(sal);

        // write above details in XML File
        TransformerFactory tF = TransformerFactory.newInstance();
        Transformer trans = tF.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\file.xml"));

        // Output write to console for your reference
         result = new StreamResult(System.out);

        trans.transform(source, result);

        System.out.println("Your file saved! in the C:\\file.xml location :-)");

      } catch (ParserConfigurationException e) {
        e.printStackTrace();
      } catch (TransformerException t) {
        t.printStackTrace();
      }
    }
}


Output :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Department>
    <Employee id="1">
        <FirtName>Skitech</FirtName>
        <LastName>krish</LastName>
        <NickName>bala</NickName>
        <salary>200000</salary>
    </Employee>
</Department>

Reading Xml File using Java Program

Hi All,


Step1: Create a xml file as the xml Standard.

<?xml version="1.0" encoding="UTF-8"?>
<stocks>
       <stock>
              <symbol>Citibank</symbol>
              <price>100</price>
              <quantity>1000</quantity>
       </stock>
       <stock>
              <symbol>Axis bank</symbol>
              <price>90</price>
              <quantity>2000</quantity>
       </stock>
          <stock>
              <symbol>Indian bank</symbol>
              <price>695</price>
              <quantity>1200</quantity>
       </stock>
          <stock>
              <symbol>Canara bank</symbol>
              <price>370</price>
              <quantity>1000</quantity>
       </stock>
          <stock>
              <symbol>Icici    bank</symbol>
              <price>180</price>
              <quantity>3000</quantity>
       </stock>
          <stock>
              <symbol>State bank</symbol>
              <price>990</price>
              <quantity>200</quantity>
       </stock>
</stocks>


Step 2: Save the file as stock.xml (user dependent format).

Java program for read above xml file in console:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class xmlRead {

    public static void main(String args[]) {
        try {

            File stocks = new File("C:\\Documents and Settings\\Sify\\Desktop\\stock.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(stocks);
            doc.getDocumentElement().normalize();

            System.out.println("XML File " + doc.getDocumentElement().getNodeName());
            NodeList nodes = doc.getElementsByTagName("stock");
            System.out.println("==========================");

            for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                System.out.println("Stock Name: " + getValue("symbol", element));
                System.out.println("Stock Price: " + getValue("price", element));
                System.out.println("Stock Quantity: " + getValue("quantity", element));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        }

    private static String getValue(String tag, Element element) {
        NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = (Node) nodes.item(0);
        return node.getNodeValue();
    }
}







output:

XML File stocks
==========================
Stock Name: Citibank
Stock Price: 100
Stock Quantity: 1000
Stock Name: Axis bank
Stock Price: 90
Stock Quantity: 2000
Stock Name: Indian bank
Stock Price: 695
Stock Quantity: 1200
Stock Name: Canara bank
Stock Price: 370
Stock Quantity: 1000
Stock Name: Icici    bank
Stock Price: 180
Stock Quantity: 3000
Stock Name: State bank
Stock Price: 990
Stock Quantity: 200
BUILD SUCCESSFUL (total time: 0 seconds)


Monday, March 25

.Bat commands

Hi ALL,

 Now I start to learn the fresh thing that is .BAT File concepts, also I tried something brand new in bat files.

 Needed Application : Notepad  
                                  Saved a file in .Bat format (Ex: sample.bat) Sample code:

@ECHO off
ECHO welcome, %username%
echo %dir%
PAUSE


Type this commend in notepad also save username.bat or else you convenient :)

 Next one somewhat good :) 

@echo off
Rundll32 user32,SwapMouseButton
msg * try this
msg * good look finding how to fix it and read my blog (http://balamr01.blogspot.in)



Once you run this bat file, it will change your mouse click option from left to right (enable the switch primary and secondary button option) 

Solution: reverts this GOTO: Control Panel-> select Mouse-> the uncheck the switch primary and secondary button option -> apply -> ok. 




Friday, December 28

Remove write protection on pen drive

Hi All,

I got the code from net :)

Here is how you can remove or uninstall write protection on pen drive. This is a common problem faced by most users. 
Often an error occurs while copying, deleting or modifying data or files for the USB. This happens because it is 'Write-Protected'. Here is a solution to the problem of the USB being write-protected. Follow the steps mentioned in this article to enable the modification, copying or deleting of files from the USB thereafter. 

Issue

This a very common problem when using USB flash drives. Sometimes when you try to copy or delete files you get an error message "Remove the write-protection or use another disk". Furthermore, it won't allow you to format it! 




Solution

To remove write protection:
  • Open Start Menu >> Run, type regedit and press Enter. This will open the registry editor.
  • Navigate to the following path:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies
  • Double click the key WriteProtect in the right pane and set the value to 0
  • In the Data Value Box, press OK
  • Exit Registry, restart your computer and then re-connect your USB pen drive to your computer.



That is it, done. Good luck!

Backup files to google drive using PHP coding

 Dear All, To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here...