Friday, August 15, 2014

Posted by Anmol Sharma
In the previous article, we discussed about two basic file handling functions in Java including searching for an existing created file in the system and creating a file using java’s inbuilt function.

In this article we will cover up the other two file handling operations which includes reading from a file and writing to a file using java’s own methods. In this program we create a file by specifying a file name, open it at the same time and add records to it as per custom format. After writing to the file, it is good practice to close it.

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

public class FileHandlingTrial {

       private Formatter file;
      
              public void openFile (){ //creating & opening a file
                    
                     try{
                           file= new Formatter("New Text Document.txt"); //will be created in default workspace folder else specify a path
                     }
                    
                     catch(Exception e){
                           System.out.println("Illegal file operation");
                                 
                           }
                     }
                    
                     public void addRecords(){// writes to the created file
                           file.format("%s %s %s", "99", "MCA", "IP University");
                    
                     }
                    
                     public void closeFile(){ //good practice to close the file after use
                           file.close();
                     }
      
}


class FileHandlingTrial1 {
      
       public static void main(String[] args){
             
         FileHandlingTrial asp = new FileHandlingTrial();
        
         asp.openFile();
         asp.addRecords();
         asp.closeFile();
             
       }
}


In this last program of file handling we will read the content added by the user.
Here also we create three methods in which first opens the file, second reads the content of the file and third one finally closes the file after reading the contents.


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



public class FileHandlingTrial {

private Scanner file;

public void openFile(){ // to open the file
      
       try{
              file = new Scanner(new File("new.txt"));
             
             
       }
      
       catch(Exception e){
             
              System.out.println("File not found");
       }
}

public void readFile(){ // to read data from the file
      
       while(file.hasNext()){
              String a=file.next();
              String b=file.next();
              String c=file.next();
              String d=file.next();
             
              System.out.printf("%s %s %s %s\n", a, b, c, d);
             
}

}

public void closeFile(){
file.close();
}
}


class FileHandlingTrial1 {
      
       public static void main(String[] args){
             
         FileHandlingTrial asp = new FileHandlingTrial();
        
         asp.openFile();
         asp.readFile();
         asp.closeFile();
             
       }
}

Screenshot // click to open a higher resolution version





Thursday, August 14, 2014

Posted by Dollar Dhingra
Hello There, this is the first part of the series Pattern Programming Questions.
The First Part is specially for beginners who are new to programming and have basic understanding of loops and printing functions. In this part, I will walk you through some basic patterns.

Pattern Questions are not only the frequently asked questions in the interviews but also help you in developing the basic logic in programming. I will explain you some of the basic ones, and leave the rest for you to try.

Following patterns will be covered:

Pattern 1:

*****
*****
*****
*****


Pattern 2:

12345
12345
12345
12345

Pattern 3:

11111
22222
33333
44444

Pattern 4:

11111
22222
33333
44444

Pattern 5:

1
12
123
1234
12345

Pattern 6:

1
22
333
4444
55555

Pattern 7:

1
2   3
4   5   6
7   8   9   10
11 12 13 14 15


Pattern 1:
Lets start with the very basic one.

*****
*****
*****
*****

In the above  pattern there are 5 columns (left to right) and 4 rows(top to bottom).

We take rows as r and columns as c and we will use 2 loops for this, one for printing the rows, and other for columns.

 pseudocode----

r=5, c=5;
for(i=0;i<r;i++)
 {
    for(j=0;j<c;j++)
      {
         printf("*");//this prints star 5 times(c times)
      }
     printf("\n");//for coming to a new line after star is printed
 }

 the printf("\n") is executed 4 times hence 4 rows will be there.

 complete program:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <stdio.h>  
  int main()  
  {  
   int r,c,i,j;  
   printf("Enter number of rows and columns: \n");  
   scanf("%d %d",&r, &c);  
  for(i=0;i<r;i++)  
   {  
    for(j=0;j<c;j++)  
     {  
       printf("*");//this prints star 5 times(c times)  
     }  
     printf("\n");//for coming to a new line after star is printed  
   }  
    return 0;  
  }  


 OUTPUT:
Enter number of rows and columns:
4 5

*****
*****
*****
*****


Pattern 2:

12345
12345
12345
12345

Now, we just have to make a small change to achieve this one:

Pseudo:
for(i=0;i<r;i++)
 {
    for(j=0;j<c;j++)
      {
         printf("%d", j+1);//printing the value of j+1 
      }
     printf("\n");
 }



 complete program:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <stdio.h>  
  int main()  
  {  
   int r,c,i,j;  
   printf("Enter number of rows and columns: \n");  
   scanf("%d %d",&r, &c);  
  for(i=0;i<r;i++)  
   {  
    for(j=0;j<c;j++)  
     {  
       printf("%d", j+1);//this prints the value of j+1 i.e: 1 2 3 4 5   
     }  
     printf("\n");//for coming to a new line after star is printed  
   }  
    return 0;  
  }  



 OUTPUT:
Enter number of rows and columns:
4 5

12345
12345
12345
12345


Pattern 3:

11111
22222
33333
44444


You guessed it right ! We will now print the value of i in place of j

Pseudo:
for(i=0;i<r;i++)
 {
    for(j=0;j<c;j++)
      {
         printf("%d", i+1);//printing the value of j+1 
      }
     printf("\n");
 }


 complete program:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
  #include <stdio.h>  
  int main()  
  {  
   int r,c,i,j;  
   printf("Enter number of rows and columns: \n");  
   scanf("%d %d",&r, &c);  
  for(i=0;i<r;i++)  
   {  
    for(j=0;j<c;j++)  
     {  
       printf("%d", i+1);   
     }  
     printf("\n");//for coming to a new line after star is printed  
   }  
    return 0;  
  }  

 OUTPUT:
Enter number of rows and columns:
4 5

11111
22222
33333
44444


Pattern 4:

*
**
***
****
*****


Now this is the last one that I will explain.

Firstly, there will be 2 for loops(for printing rows and columns)

Second thing to be noticed is that there are N number of stars in Nth row,
i.e. 1 star in 1st row
      2 stars in 2nd row
      3 stars in 3rd row and so on...


so, in the second for loop we have to restrict j (number of columns) till i (number of rows)

Pseudo:
for(i=0;i<r;i++)
 {
    for(j=0;j<=i;j++)//restricting the value of j till i
      {
         printf("%d", i+1); 
      }
     printf("\n");
 }



 complete program:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
  #include <stdio.h>  
  int main()  
  {  
   int r,c,i,j;  
   printf("Enter number of rows and columns: \n");  
   scanf("%d %d",&r, &c);  
  for(i=0;i<r;i++)  
   {  
    for(j=0;j<=i;j++)  
     {  
       printf("*");   
     }  
     printf("\n");  
   }  
    return 0;  
  }  


 OUTPUT:
Enter number of rows and columns:
5 5

*
**
***
****
*****
Now you can try the following patterns, It is recommended that you minimize the the browser and try them before looking at the solutions.

 

Pattern 5:

1
12
123
1234
12345



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
  #include <stdio.h>  
  int main()  
  {  
   int r,c,i,j;  
   printf("Enter number of rows and columns: \n");  
   scanf("%d %d",&r, &c);  
  for(i=0;i<r;i++)  
   {  
    for(j=0;j<=i;j++)  
     {  
       printf("%d", j+1);   
     }  
     printf("\n");  
   }  
    return 0;  
  }  



Pattern 6:

1
22
333
4444
55555


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
  #include <stdio.h>  
  int main()  
  {  
   int r,c,i,j;  
   printf("Enter number of rows and columns: \n");  
   scanf("%d %d",&r, &c);  
  for(i=0;i<r;i++)  
   {  
    for(j=0;j<=i;j++)  
     {  
       printf("%d", i+1);   
     }  
     printf("\n");  
   }  
    return 0;  
  }

 

Pattern 7:

1
2   3
4   5   6
7   8   9   10
11 12 13 14 15


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
  #include <stdio.h>  
  int main()  
  {  
   int r,c,i,j, count=0;  
   printf("Enter number of rows and columns: \n");  
   scanf("%d %d",&r, &c);  
  for(i=0;i<r;i++)  
   {  
    for(j=0;j<=i;j++)  
     { count++; 
       printf("%3d", count); // "%3d" is used in printf for better indentation   
     }  
     printf("\n");  
   }  
    return 0;  
  }  


I will get back to you with some more complex patterns.


 Please share our blog and like our Facebook Page, This will help us grow. :)

Tuesday, August 12, 2014

Posted by Anmol Sharma
Java provides File class in ‘java.io’ package for handling all basic and necessary file operations and methods used for file handling like reading the contents of a file, writing to a file, searching for a file, determining the path of the file stored on a disk, etc. File class contains number of methods for performing specific operations on a file, few of which are used in this article.

In this program, the user is checking for the existence of a particular file stored on system’s hard disk. File class of Java IO package has been used to provide access to methods like exists(), getName() which checks for the file and if found returns the message else gives user defined message.

import java.io.File; //file class for basic file operations

class FileHandlingTrial{
               
         public static void main(String[] args) {
                               
  File asp = new File("C:\\file\\info.txt"); // constructor takes the path of the file already existing on the system
                               
             if(asp.exists()) // built in method to test whether a specified file exists or not.
                                               
                        System.out.println(asp.getName() + "File Found"); // prints the message along with file name
                                               
                                        else
                        System.out.println("File Not Found");
                               
                }
}


In the previous program we checked for an already created file on the system. We can also create a file using the program with help of facilities provided by java.io package

import java.util.*;

class FileHandlingTrial{
               
                public static void main(String[] args) {
                               
                                final Formatter asp; //formatter print strings to file
                               
                                try{

                                      asp = new Formatter("c://file//trial.txt"); //provide path of file where it will be stored
                                               
                                                System.out.println("File Created");
                                }
                               
                                catch(Exception e){
                                               
                             System.out.println("Error"); // for possible mistyping of wrong or illegal folder location like specifying a drive which does not exist on system.
                                }
                                               
                }
}


In the next article which will be part 2 of file handling, reading from a file and writing to a file will be discussed. Thanks folks for reading. 

Screenshot // click to open a higher resolution version





Posted by Anmol Sharma
Exception handling in java is similar as in C#. There are couple of differences like java allows checked exceptions which are handled by the caller of the program. Another minor difference is in the finally statement which can have return and break statement which is not the case in C#.

Refer to previous article for Introduction to Exception handling Exception Handling Basics in C#

Following code illustrates the basic concept of exception handling dealing with divide by zero exception in Java. As we know exception is any abnormal condition in a program which abrupt the normal flow of the program. Exception handling allows users to take corrective measures and have easy to understand information returned to them in case an exception arises.


import java.util.*;

public class ExceptionTrial {
               
                public static void main(String[] args){
                Scanner input = new Scanner(System.in); //allows the user to input values
               
                int x=1;
               
                do{
               
                try{ //put the code in try block which may raise an exception
                               
               
                System.out.println("Enter a number  :");
                int n1=input.nextInt();
                System.out.println("Enter another number to divide");
                int n2=input.nextInt();
                int sum = n1/n2;
               
                System.out.println(sum);
                x=2;
                }
               
                catch(Exception e){   //handles the exception, lets the user know whats wrong.
                               
                                System.out.println("You can not divide a number by zero");
                               
                }
                }while(x==1); // loop to let user enter correct value after encountering exception
               
               
                }
            
}

Screenshot // click to open a higher resolution version