Saturday, August 6, 2011

syntax error unexpected EOF PHP

I got a wired error during developing a php page. Eclipse shows a red mark at the end of the php page and resting the mouse on it gives "syntax error unexpected EOF" and when i run the script on xampp it says that it cannot parse.

The red mark at the bottom of the page isn't where the error is because even after deleting a line from the last it doesn't make the error go away.

The reason for this error is not properly closing a delimiter. This can be a bracket of a for statement or if statement or function block. Well for me i had not closed a foreach loop. :(

Wednesday, July 27, 2011

Find out what port MySQL is using / Change port mysql is using

Sometimes you forget the port mysql is running on.

Solution :-

1.) Open my.ini file
2.) locate [mysqld]

# The TCP/IP Port the MySQL Server will listen on
port=3306

You can change the port mysql listens to my by assigning a new value to port. After that make sure to restart mysql server.

#2002 cannot log in to the MYSQL server

I opened phpMyAdmin and tried to log into it , even though i typed in the correct username and password i got the following error message

#2002 cannot log in to the MYSQL server

I installed mysql server on port 3305. The default port that it installs to is 3306 and that is the same port phpMyAdmin would try.

Solution :-

open config.inc.php. Found under the phpMyAdmin folder
locate the following line

$cfg['Servers'][$i]['port'] = 'x';

x = port that mysql listens

Make x the value mysql is set to run on. If you cannot remember the port that it runs on then goto -> http://scriptche.blogspot.com/2011/07/find-out-what-port-mysql-is-using.html

Monday, July 25, 2011

Saturday, July 23, 2011

Linkage Properties Dialog Box in Flash CS5 Where ?

Hello Everyone. In this blog post i will show you how to access the linkage properties of a symbol item. I found out the technique on accomplishing this after spending several hours googling and reading forum postings. Anyway, finding these are tough especially if you are very new to flash development.  I hope the solution i provide to you below helps you.

Click on the symbol item on library tab and select properties
Next click on Advanced



Wednesday, June 22, 2011

install flex_sdk_4.1 on windows 7

Well this is no big deal. You only have to insert the bin folder path to the path environment variable

On my computer the path is

D:\Program Files (x86)\flex_sdk_4.1\bin

Usually on windows you append this to the path variable.

intersection of two int arrays - java

public class Test {

 public static void main(String[] args) {
  printAll(intersection(new int[]{-5} ,new int[]{6,55,66,-4,-5} ) );
 }

 static int [] intersection(int array1[] , int array2[]){

  java.util.ArrayList<Integer> arrayList = new java.util.ArrayList<Integer>();

  for(int outer=0; outer< array1.length ; outer++){

   for(int inner=0; inner < array2.length ; inner++){

    if(array1[outer] == array2[inner]){
     arrayList.add(array1[outer]);
     // or arrayList.add(array2[outer]); will do
    } 
   }
  }

  int intersectionArray[] = new int[arrayList.size()];

  // now add all the elements in arrayList to intersectionArray[] 

  for(int i = 0 ; i  < arrayList.size() ; i++){
   intersectionArray[i] = arrayList.get(i); 
  }

  return intersectionArray;

 }

 static void printAll(int array[]){

  for(int i =0 ; i < array.length ; i++){
   System.out.println(array[i]);
  }
 }

}

indexOf character in word - return all indices of occurance - java

static int [] indexOfArray(char character, String word){

  java.util.ArrayList<Integer> arrayList = new java.util.ArrayList<Integergt;();

// loop through word to find the occurrence of character

  for(int i = 0 ; i < word.length() ; i++){
   if( word.charAt(i) == character){
    arrayList.add(i); // if character found add i to arrayList
   }
  } 

  int [] array = new int[arrayList.size()];

  int i =0;

// add all elements in arrayList to int array

  for(int x : arrayList){
   array[i] = arrayList.get(i);
   i++;
  }

  return array; 
 }

 static void printAll(int array[]){

  for(int i =0; i < array.length ; i++){
   System.out.println(array[i]);
  }

 }

Unable to locate tools.jar. Expected to find it in ..\Java\jre6\lib\tools.jar and installing Ant


How to resolve this error in windows

So this is a very common error. Almost everyone would stumble upon this one in a while. I myself got myself tangled in this error even though i closely followed the installation instructions (I installed ant in the way i mentioned below in this post) . Anyhow without further ado i am going to reveal the solution to solve this problem . The solution is a very simple one. You have to add the JAVA_HOME variable to the windows environment.

JAVA_HOME = C:\Program Files (x86)\Java\jdk1.6.0_23

If you get the error in linux this is how you resolve it


add the following to your .bashrc file
export JAVA_HOME=/somedirectory/jdk1.5.0_08/
And reload the .bashrc file

And after adding the windows environment variables, and began to run without much hesitation.
Well for those of you who wanna know how to install ant can read the clearly listed instructions
below. Should you happen to come across any difficulties, please don't hesitate to drop
a comment in the comments section below. I will be more than willing to help you with resolving
your issue.

Installing ant on windows

Step 1:- Goto http://ant.apache.org and download ant-current-bin.zip file.

Step 2:- Extract the zip file

Step 3:- Set environment variables. Path = location of bin folder (Eg:- D:\Program Files (x86)\apache-ant-1.8.2\bin) ANT_HOME = Location of ant home folder (Eg:- D:\Program Files (x86)\apache-ant-1.8.2) ANT_OPTS=-Xmx256M 

Notice i installed ant in drive D instead of C. You might want to install in drive C or in a entirely different drive. Its upto you guys to decide where you wanna install. Personally I prefer not to install my programs on drive C.

Installing ant on linux


Well how to you actually install ant on linux? I took the easy way out by telling apt-get to do all the hardwork
apt-get install ant
Well certainly apt-get saved my day :). Well but there is still a small configuration part left to do Add the following statements into your .bashrc file 

export ANT_OPTS="-Xmx256M"
export ANT_HOME=/usr/bin/ant
export PATH=$PATH:/usr/bin/ant/bin



Monday, June 20, 2011

isNumber check for String in java

static boolean isNumber(String number){

  if(number.charAt(0)=='-'){

   for(int i = 1 ; i < number.length() ; i++){
    if( Character.isDigit(number.charAt(i))){

    }
    else{
     return false;
    }
   }
  }
  else{

   for(int i = 0 ; i < number.length() ; i++){
    if( Character.isDigit(number.charAt(i))){

    }
    else{
     return false;
    }
   }

  }

  return true;
 }

Well the above code can be simplified alot with the use of ternary operator
 static boolean isNumber(String number){

  for(int i = number.charAt(0)=='-' ? 1: 0 ; i < number.length() ; i++){
    if( Character.isDigit(number.charAt(i))){
    }
    else{
     return false;
    }
   }
  return true;
  
 }

Tuesday, June 14, 2011

Validate a email address in java

public static void main(String[] args) {

  System.out.println(vaidateEmailAddress("exa.mple@gmail.com") );
  System.out.println(vaidateEmailAddress("exa..mple@gmail.com") );

 }


 static boolean vaidateEmailAddress(String email){

  boolean valid = false;

  String domain[] = {"gmail.com" , "yahoo.com", "hotmail.com" };
  String localPart = email.substring(0, email.indexOf('@', 0));
  String domainPart = email.substring( localPart.length() + 1, email.length());

  int noOfAts = 0;

  for(int i = 0 ; i < email.length(); i++){

   if(  email.indexOf('@', i) != -1){
    noOfAts++;
    i = email.indexOf('@', i);
   }
  }

  if(noOfAts > 1 || noOfAts == 0) {
   // if more than one @ symbol appears no point in further checking. Its a invalid email address
   return false;
  }
  else{
   // now that it has been found that there is only one @ symbol lets check the domain 

   for( int i = 0 ; i < domain.length ; i++){
    if( domainPart.equals(domain[i])){
     valid = true;
     // still further processing of the string is needed. Thats why it doesn't return true
    }
   }
  }

  // checks for the presence of invalid characters in the local part

  if(localPart.charAt(0) == '.' || localPart.charAt(localPart.length() -1) == '.'){
   return false;
  }
  else{

   for(int i =0 ; i < email.indexOf('@', 0); i++){

    if(validCharacter(email.charAt(i)) ){
    }
    else if(email.charAt(i)== '.' && email.charAt(i+1)== '.'){
     return false;
    }
    else if(email.charAt(i)=='.'){
    }
    else{
     return false;
    }
   }
  }
  return valid;
 }


 static boolean validCharacter(char c){

  char validSymbols[] = {'!', '#' ,'$' ,'%' ,'&' ,'\'' ,'*' ,'+', '-', '/', '=' ,'?', '^','_','`' ,'{' ,'|' ,'}', '~'}; 

  for(int i =0 ; i < validSymbols.length; i++){
   
   if(validSymbols[i] == c ){
   }
   else{
    if(Character.isLetter(c)){
    }
    else if(Character.isDigit(c)){ 
    }
    else{
     return false;
    }
   }
  }
  return true;
 }
}

Runtime Exceptions Examples - Java

1.) Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6

int array[] = {4,5,22,33};
int a = array[6];


2.) Exception in thread "main" java.lang.NullPointerException

int array2[]  = null;
int b = array2[1];


3.) Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

String string  = "Hello World";
String subString = string.substring(-1, 5);


4.) Exception in thread "main" java.lang.ArithmeticException: / by zero

int a = 4;
int b = a/0;


5.) Exception in thread "main" java.util.EmptyStackException

Stack<integer> ese = new Stack<integer>();
ese.pop();


6.) NumberFormatException

int no=0;
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inputStreamReader);
no =  Integer.parseInt(in.readLine() );


7.) java.lang.StackOverflowError

Call this method with a large long value

eg:- sof(7000);

static long sof(long n){
if(n==4) return 1;
else return n + (sof(n-1)) ;
}

Read text file into 2D array - Java

The text file is read line by line.

String array[x][y] ;

x - xth line in text file
y - yth word

So

array[x][y] - yth word in xth line

Here is the code

 static void readTo2DArray() throws IOException {

  FileInputStream fstream = new FileInputStream("test.txt");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));

  String strLine;
  int arraySize = 6;
  String array[][] = new String[arraySize][];
  int index = 0;
  while ((strLine = br.readLine()) != null) {
   
   if (index >= arraySize - 1) {
    System.out.println("Error : Increase array size !");
    break;
   }
   array[index] = strLine.split(" ");
   index++;
   
  }

  printAll(array);

 }

 static void printAll(String array[][]) {

  for (int i = 0; i < array.length; i++) {

   if (array[i] != null) {
    for (int j = 0; j < array[i].length; j++) {
     System.out.print(array[i][j] + " ");
    }
    System.out.println(" ");
   }
  }

 }




Print All Digits In a int - java

Method 1:- Using % operator. Print from left to right

static void printAll(int number) {

  while (number > 10) {
   int digit = number % 10;
   number = (number - digit) / 10;
   System.out.print(digit + " ");
  }
  System.out.print(number);
 }


Method 2:- Convert int to a String and then printing individual characters.

static void printAll(int number) {

  String numberString = Integer.toString(number);

  for(int i = numberString.length()-1 ; i >=0 ; i--){
   System.out.print(numberString.charAt(i) + " ");
  }

 }


You can make it print the digits print in the reverse direction by changing the parameters of the for loop.

Reverse a int in java

Method 1 - Without using any other data structure. Making extensive use of % operator. I love this method and you will love it too.

static int rev(int number) {

  int rev = 0;

  while (true) {
   int digit = number % 10;
   number = (number - digit) / 10;
   rev += digit;

   if (number < 10) {
    rev *= 10;
    rev += number;
    break;
   } else {
    rev *= 10;

   }
  }

  return rev;
 }
Method 2 - Using StringBuffer and String
static int rev2(int number){

  int rev2 = 0;
  String numString = Integer.toString(number);
  String rev2String = "";
  StringBuffer stringBuffer = new StringBuffer();

  for(int i = numString.length() - 1 ; i >=0; i--){
   stringBuffer.append(numString.charAt(i));
  }

  rev2String = stringBuffer.toString();
  rev2 = Integer.parseInt(rev2String);  

  return rev2;
 }

Monday, June 13, 2011

Determine whether a decimal number is odd or even

Method 1:-

static void method1(int number){

  if(number % 10 == 1 || number % 10 == 3  || number % 10 == 5  || number % 10 == 7 || number % 10 == 9){
   System.out.println("ODD");
  }
  else{
   System.out.println("EVEN");
  }

 }


Method 2:-

static void method2(int number){

  if(number % 2 == 1){
   System.out.println("ODD"); 
  }
  else{
   System.out.println("EVEN");
  }
 }


Method 3:- Using integer class to convert int to binary and check whether least signifiant bit is a one or zero.

lsb = 1 => odd
lsb = 0 => even

static void method3(int number){

  if(Integer.lowestOneBit(number) == 1){
   System.out.println("ODD");
  }
  else{
   System.out.println("EVEN");
  }
 }

replace Vector element with new one

static void foo() {

  Vector<String[]> vector = new Vector<String[]>();

  String array1[] = { "word1", "word2", "word3" };
  String array2[] = { "word4", "word5", "word6" };
  String array3[] = { "word7", "word8", "word9" };

  vector.add(array1);
  vector.add(array2);

  printall(vector);
  
  vector.set(1, array3);
 
  printall(vector);

 }

 static void printall(Vector<String[]> vector) {

  System.out.println("\n");

  for (int i = 0; i < vector.size(); i++) {

   for (int j = 0; j < vector.get(i).length; j++) {
    System.out.println(vector.get(i)[j]);
   }

  }

 }
}


Modify a String element of a Vector String Array

static void foo(){
  
  Vector<String []> vector = new Vector<String []>();
  
  String array1[] = {"word1","word2","word3"};
  String array2[] = {"word4","word5","word6"};
  String array3[] = {"word7","word8","word9"};
  
  vector.add(array1);
  vector.add(array2);
  vector.add(array3);
  
  printall(vector);
   
  String newarray[] = vector.get(1);
  newarray[0]="newword";
  
  printall(vector);
  
 }
 
 static void printall(Vector<String []> vector){
 
        System.out.println("\n");
    
        for(int i =0; i < vector.size();i++){
    
            for(int j=0; j < vector.get(i).length ; j++){
            System.out.println(vector.get(i)[j]); 
            }
        
    }

remove line break and carriage return from string java

Using String replaceAll

String s1 = "hello\r world \nhello world";
System.out.println(s1);
String s2 = s1.replaceAll("[\n\r]", "");
System.out.println(s2);


Here the first argument is replaced with the second argument.

First argument = regular expression used to specify what you want to replace
Second argument = string


I will show you a manual method to replace newline and carriage return from a string

Method 1:- Using two for loops , substring , indexOf , ternary operator

String s1 = "hello\r world \nhello world";

  String s2 ="";

  for(int j =0 ; j < 2 ; j++){
   
   for(int i = 0 ; i < s1.length() ; i++){

    if(s1.indexOf( j==0 ? '\n' : '\r' , i) != -1){
     s2 += s1.substring(i, s1.indexOf(j==0 ? '\n' : '\r', i));
     i = s1.indexOf(j==0 ? '\n' : '\r', i);
    }
    else{
     s2+=s1.substring(i, s1.length());
     break;
    }
   }

   if(j==0){
    s1 = s2;
    s2="";
   }
  }
  System.out.println(s2);


Method 2:- Using StringBuffer. This is a much cleaner method
StringBuffer stringBuffer = new StringBuffer();
  
  String s1 = "hello\r world \nhello world";
  
  for(int i = 0 ; i < s1.length() ; i++){
   
   if(s1.charAt(i) != '\n' && s1.charAt(i) != '\r' ){
    stringBuffer.append(s1.charAt(i));
   }
  }
  
  System.out.println(stringBuffer.toString());

Sunday, June 12, 2011

Factorial in java

Method 1 Using a for loop

Well the simplest is to use a for loop to find the factorial of a number.

static long factorial(int factorial) {

  int fact = 1;

  for (int i = factorial; i > 0; i--) {
   fact *= i;
  }

  return fact;
 }


Method 2 : Using recursion

public static long factorial( int n )
    {
        if( n <= 1 )     // base case
            return 1;
        else
            return n * factorial( n - 1 );
    }

Friday, June 10, 2011

Pass a array by reference to a method in java

Well what happens if you do something like this

void method1(){
int array[] = {3,4,33,22};
method2(array);
}

void method2(int array[]){
// modify array contents
}

The modifications that you do inside method2 wont reflect once the method returns. So how you make the changes that happen inside method2 to reflect in method1 even after it returns ? Well the answer in C/C++ would be to pass by reference. But how do you do that in java? Here's the trick. You actually wrap the int array inside a object and pass the objectname.arrayname to the method.

class intarray{
int array[] = {3,4,33,22};
}


void method1(){
intarray object = new intarray();
method2(objectarray);
}

void method2(int array[]){
// modify array contents
}

So in this case whatever you do to the array from method2 once it returns the changes are seen in method1 as well.

Shuffle int array java - random swapping

import java.util.Random;
import java.util.Random;

class integer {
 // this class is created to pass the array as a reference
 int array[] = { 55, 44 };
}

public class shuffle {

 public static void main(String[] args) {

  integer object = new integer();

  shuffleByRandomSwapping(object.array, 2);
  printAll(object.array);
 }

 static void printAll(int array[]) {

  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i]);
  }

 }

 static void shuffleByRandomSwapping(int array[], int amount) {

  Random generator = new Random();

  if (array.length == 1) {
   // no meaning of swapping
   return;
  } else

   for (int i = 0; i < amount; i++) {

    if (array.length == 2) {

     if (amount % 2 != 0) {
      // just a simple swap
      int temp = array[0];
      array[0] = array[1];
      array[1] = temp;
     } else {
      // no effective swapping takes place
      return;
     }
    } else {

     int index1 = generator.nextInt(array.length);
     int index2 = generator.nextInt(array.length);

     while (index1 == index2) {
      // if index1==index2 no swapping takes place
      index2 = generator.nextInt(array.length);
     }

     int temp = array[index1];
     array[index1] = array[index2];
     array[index2] = temp;

    }
   }
 }
}

Multiply two arrays using two threads

import java.util.Random;

public class Matrix implements Runnable {

 static int matrixSize = 5000;

 static long mult = 0;
 static int m1[];
 static int m2[];

 static void init() {

  m1 = new int[matrixSize];
  m2 = new int[matrixSize];

  Random randomGenerator = new Random();

  for (int i = 0; i < matrixSize; i++) {
   
   m1[i] = randomGenerator.nextInt(10);
   m2[i] = randomGenerator.nextInt(10);

  }

 }

 public static void main(String[] args) {
               
  init();
                // create two threads
  Thread th1 = new Thread(new Matrix()); 
  Thread th2 = new Thread(new Matrix());

                // sets names
  th1.setName("1");
  th2.setName("2");

                // start threads
  th1.start();
  th2.start();

  try {
                        // joins threads to main thread
   th1.join();
   th2.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }

  System.out.println("mult" + mult);
 }

 public void run() {

  if (Thread.currentThread().getName().equals("1")) {
   long localMult = 0;
   for (int i = 0; i < matrixSize / 2; i++) {
    localMult += m1[i] * m2[i];
   }
   sum(localMult);

  } else if (Thread.currentThread().getName().equals("2")) {
   long localMult = 0;
   for (int i = matrixSize / 2; i < matrixSize; i++) {
    localMult += m1[i] * m2[i];
   }
   sum(localMult);
  }
 }

 synchronized void sum(long amount) {
// this method is synchronized because this updates global variable
  System.out.println("Sum " + amount);
  mult += amount;
 }
}

For-Each Loop Java

import java.util.ArrayList;

public class ForEach {
 
 static void array(){
 
  double[] array = {9.5, 4.3, 3.8, 8.8};
  double sum = 0;
  
  for (double d : array) {  
   sum += d;
  } 
  
  System.out.println(sum);
  
 }
 
 static void arrayList(){
  
  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  arrayList.add(1);
  arrayList.add(2);
  arrayList.add(3);
  arrayList.add(4);
  arrayList.add(5);
  
   for (int integer : arrayList)
        System.out.print(integer + " ");
 }
 
 public static void main(String args[]){
  
 array();
 arrayList();
  
 }
 
}

I will be updating this post to show how to use for-each loop with other datastructures.

Wednesday, June 8, 2011

How to read a properties file - java

The properties file

message = How are you

And the java code to read it

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class testmain {

    public static void main(String[] args) {
     
       Properties props = new Properties();
       
       try {

              props.load(new FileInputStream("message.properties"));

              String message = props.getProperty("message");

              System.out.println(message);

               }

              //catch exception in case properties file does not exist

              catch(IOException e)
              {
              e.printStackTrace();
              }          
    }
}

ant Unable to locate tools.jar. Expected to find it in /usr/lib/jvm/java-6-openjdk/lib/tools.jar

add the following to your .bashrc file

 export JAVA_HOME=/somedirectory/jdk1.5.0_08/

And reload the .bashrc file

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Well i was screwing around with the system and i found that i forgot to actually start mysql server. You start mysql server by running mysqld. And now you try running mysql. It works right.

libaio.so.1 shared object file not found

Installing software under linux is a nightmare sometimes. I installed mysql but when i tried to start it i got

libaio.so.1 shared object file not found

Error msg. Oops so now what to do. Well the obvious solution is to somehow install that file into your system. But how in the heck do you do it ?

Well try running this command

sudo aptitude install libaio-dev

And then run mysqld. Wow where did the error go ?

Sunday, May 29, 2011

Writing infinite loops in java

infinite while loop

while{true}{

}

infinite for loop

for(;;);

infinite do while loop

do {  
} while (true);

Monday, April 11, 2011

Add hashset integers to int array in java

static int [] hashset_to_int_array(HashSet<Integer> hs){
  
  int array[] = new array[hs.size()];
  
  Iterator itr = hs.iterator();

  int i=0;

  while(itr.hasNext()){
  array[i++] = Integer.parseInt(itr.next().toString());
  }

  return array;
 }

take mirror image of a int array in java

Okay so lets say you have a array and you just wanna take the mirror image of it. how do you do it ? well there are several ways of doing it. One way is to just make another array , copy the first one to the second one by looping through the first one in the reverse direction. like this.

// this is the first array
int firstArray [] = {5 , 7, 98 , 44, 33 };

// this is how you make the second array
int secondArray[] = new int[firstArray.length];


Now you have to insert the above two arrays within a for loop to make the copy in reverse direction.

for(int i = firstArray.length - 1 ; i >= 0 ; i--){
secondArray[firstArray.length - 1- i]=firstArray[i];
}


wow now the secondArray is the mirror image of the first one. This method as you can see does not modify the firstArray. What you can do is make firstArray refer to the secondArray. Like this

firstArray = secondArray;


Now you may be wondering what happened to the firstArray memory segment. Well that will be garbage collected by the garbage collector because there is no reference to it in the code. Hey but this method is not recommended because it makes another copy of the original.

The one iam gonna show you below actually does the modification within the first array itself without requiring another array. but this method is a bit tricky. If i have time in the future i will show you how this code segment works using a diagram.

public static void mirror_int_array(int[] array) {

  if (array.length % 2 == 0) {

   int temp = 0;

   for (int i = 0; i < array.length / 2 - 1; i++) {

    temp = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = temp;

   }

  }

  else {

   int temp = 0;

   for (int i = 0; i < (array.length + 1) / 2 - 1; i++) {

    temp = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = temp;

   }

  }

 }

swap 2 integers in int array when index is specified java


 public static void swap_int_array(int []array , int index1 , int index2){
  int temp=array[index1];
  array[index1] = array[index2];
  array[index2]= temp; 
 }

rotate a int array by specific amount java

public class rotate {

 public static void rotate_int_array(int []array , int amount){

  int array_size = array.length ;

  if(amount % array_size ==0) return;

  if(amount < 0){

   amount = (-1) * amount;

   int temp=0;

   for(int i =0 ; i < amount ; i++){

    temp=array[array.length-1];
    for(int shift=array.length-1; shift >0 ; shift--){
     array[shift] = array[shift-1]; 
    }
    array[0] = temp;
   }
  }
  else{

   if(amount > array_size) amount = amount % array_size;

   int temp=0;

   for(int i =0 ; i < amount ; i++){

    temp=array[0];
    for(int shift=0; shift < array.length -1 ; shift++){
     array[shift] = array[shift+1]; 
    
                                }
    array[array.length -1] = temp;
   }
  }
 }
}

Saturday, April 9, 2011

remove numbers that are outside the range from int array java

The code below removes any negative numbers from the supplied array that are outside the range and returns a new array.

static int[] remove_outside_range(int array[] , int lower_bound , int upper_bound){

ArrayList<Integer> al = new ArrayList<Integer>();

    for(int i=0; i < array.length; i++){

    if(array[i] > lower_bound){
    al.add(array[i]);
    }

    if(array[i] < upper_bound){
    al.add(array[i]);
    }

}

    int new_array[] = new int[al.size()];

    for(int i =0 ; i < al.size() ; i++){
    new_array[i] = al.get(i);
    }

    return new_array;
}

remove negative numbers from int array java

Well you may be wondering how on earth can you remove negative numbers from a int array. You cannot physically remove negative numbers that would result in a reduction in the size of the array because arrays are immutable. One thing that you can do is that if the array is used in a situation where certain numbers are ignored then you can assign that number in place of negatives. Like this

int myArray[] = {6,-5,44,33,2,-66,7};

int x = 0;  // here x is a number that has no effect on the array's use

for(int i =0; i < array.length; i++){

if(myArray[i] > 0 ) myArray[i]=x;

}

}


The other thing that you can do is copy only the positive numbers to a new array. Wow thats fun right. But the problem is how can you determine the size of the new array ? Well obviously you can loop throught the first array once to find out the number of positive integers. And next create a new array whose length is equal to that positive integer count.

int myArray[] = {66,88,4,-4,66,-33};

int count = 0 ;

for(int i =0; i < myArray.length; i++){

if(myArray[i] >=0) count++;

}


next step is to create a new array whose size = count

int newArray[] = new int[count];


and the last step is to loop throught the myArray once again and copy only the positives

int position = 0;

for(int i =0; i < myArray.length; i++){

if(myArray[i] >=0) newArray[position] = myArray[i];
position++;
}


Okay so you end up with two arrays. any newArray contains the required result. However you can make myArray to refer to newArray and make the old reference to myArray garbage collected.

myArray = newArray;


Okay so we have removed negative integers by using two loops.

The method below makes use of arrayLists. It first scans through the array and inserts the positive integers into a arraylist. Next a new array is created whose size matches the arraylist. And the array list contents are then copied to the new array. And finally this method returns the newly created int array reference.

static int[] remove_negative(int array[]){

ArrayList<Integer> al = new ArrayList<Integer>();

for(int i =0; i < array.length; i++){

if(array[i] >= 0){
al.add(array[i]);
}

}

int new_array[] = new int[al.size()];

for(int i =0 ; i < al.size() ; i++){
new_array[i] = al.get(i);
}

return new_array;
}

remove duplicates from int array in java

Ok so now you have a int array that has duplicate integers in it and you wanna remove them and have only unique elements. This is how i will do it.

Step 1:- Copy all the int elements into a HashSet. Reason for doing this is that the HashSet only stores unique elements.

Step 2:- Create a int array of size = HashSet's size

Step 3:- Copy all the the HashSet elements into the newly created int array

static int [] remove_duplicates(int array[]){

HashSet<Integer> hs = new HashSet<Integer>();

for(int i =0 ; i < array.length ; i++){
hs.add(array[i]);
}

int new_array[] = new int[hs.size()];

Iterator<Integer> itr = hs.iterator();
int i =0;
while(itr.hasNext()){
new_array[i]=itr.next();
i++;
}

return new_array;
}

validate a ip address in java (ipv4)


static boolean validate(String ipv4_address) {

  int seperators = 0;
  int digits = 0;
  int partval = 0;

  if (ipv4_address.length() > 16)  return false; // length condition satisfied
  
  else {
    for (int i = 0; i < ipv4_address.length(); i++) {

      if (ipv4_address.charAt(i) == '.') {
      seperators++;
      digits = 0;
      partval = 0;
       
        if (seperators >= 4)
        return false; // checked the no of . 's in the address
        } else {

            if (!Character.isDigit(ipv4_address.charAt(i))) {
            return false;
            }
     
          partval = partval * 10 + Integer.parseInt(Character.toString(ipv4_address.charAt(i)));
    
             if (++digits > 3)
             return false;
             
               if (digits == 3) {

                 if (partval > 255) return false;
               }
       }
    }

  }

  return true;
}

java generate random number within range

static int randomNumberWithinRange(int lower,int upper){
  
  Random rnd = new Random();
  
  return lower + rnd.nextInt(upper-lower);
}

draw square shape in command prompt java (no fill)

 public static String outline(char c,int size, int spaces_from_left_margin,int spaces_from_top, int spaces_from_bottom){
  
  StringBuffer sb = new StringBuffer();

  for(int i = 0 ; i <spaces_from_top;i++) sb.append("\n");

  for(int outer=0; outer < (size) ; outer++){

   for(int sflm=0 ; sflm < spaces_from_left_margin ; sflm++){
    sb.append(" ");     
   }

   if(outer!=0 && outer!=(size-1)){
    
    sb.append(c);

    for(int inner=0; inner < (size -2) ; inner++){
     sb.append(" ");  
    }

    sb.append(c);    
    sb.append("\n");
   
   }
   
   else{
    
    for(int inner=0; inner < size ; inner++){
     sb.append(c);
    }
   
   sb.append("\n");

   }
   
  }
  
  for(int i = 0 ; i <spaces_from_bottom;i++) sb.append("\n");
  
  return sb.toString();

 }

draw square on command prompt in java (fill)

public static String fill(char c,int size, int spaces_from_left_margin,int spaces_from_top , int spaces_from_bottom){

 StringBuffer sb = new StringBuffer();

  for(int i = 0 ; i < spaces_from_top;i++) sb.append("\n");
 
  for(int outer=0; outer < size ; outer++){

  for(int sflm=0 ; sflm 7lt spaces_from_left_margin ; sflm++){
  sb.append(" ");     
  }

  for(int inner=0; inner < size ; inner++){
  sb.append(c);
  }

  sb.append("\n");
  }

  for(int i = 0 ; i < spaces_from_bottom;i++) sb.append("\n");
  
  return sb.toString();
}
Below is the screenshot of the output when the method is called with fill('*',10,10,10,10).

Monday, February 21, 2011

java program that generates random number of given length

The code below generates a random number of a required length and returns it. Here a while loop is utilised to to loop through a given no of times. You could use a for loop or a do while loop too. Within the while loop, the nextInt method is called on the random instance to generate a random number. This random number is appended to a string instance. You could improve the string manipulation performance by making use of a Stringbuilder. I will try to show an example which incorporates a StringBuilder at a later time.
public class Main {

    static int generate(int length){

        Random r = new Random();

         String number="";

         int counter=0;

         while(counter++< length) number+= r.nextInt(9);

        return Integer.parseInt(number);

    }

    public static void main(String[] args) {
   
        System.out.println(generate(8));

    }
}

Wednesday, February 16, 2011

Hello World in Scheme

Iam learning scheme and this is my first program. Everyone starts with a simple hello world program and so here it is.



Well its very simple