Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: nullpointerexception bug

  1. #1
    Junior Member
    Join Date
    Jul 2013
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default nullpointerexception bug

    This program is to manipulate median of an array.it returns NullPointerException.i have tried it .plz any1 to rectify the bug.
    thanxs in advance.

    import java.io.*;
     
    public class media {
     
    	@SuppressWarnings("null")
    	public static void main(String[] args) {
    		int i=0,j=0,n=0;
     
    	      float median;
    		float t; 
    	     int []a=null;
    	     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));                                                      
    	       System.out.println("Enter the number of items\n");                  
    	        try {
    				n=Integer.parseInt(br.readLine());
    			} catch (NumberFormatException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    	        System.out.println("Input values \n");  
    	       for( i=1;i<n;i++)
    			try {
    				a[i]=Integer.parseInt(br.readLine());
    			} catch (NumberFormatException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
     
    	    /* Reading items in array a  */
     
     
    	    /* Sorting begins */
    	for (i = 1 ; i <= n-1 ; i++)                            
    	       {     /* Trip-i begins  */
    	for (j = 1 ; j <= n-i ; j++)                         
    	          {                                                    
    	              if (a[j] <= a[j+1])                              
    	              { /* Interchanging values */
     
    	                t = a[j];                                      
    	                a[j] = a[j+1];                                 
    	                a[j+1] = (int) t;                                    
    	              }                                                
    	              else continue ;                                     
    	          }                                                    
    	       } /* sorting ends */
    	/* calculation of median  */
    	if ( n % 2 == 0)                                        
    	          median = (float) ((a[n/2] + a[n/2+1])/2.0) ;                   
    	       else                                                    
    	          median = a[n/2 + 1];                                 
     
    	    /*  Printing */
    	for (i = 1 ; i <= n ; i++)  
    	{
    	          System.out.println(a[i]); 
    	}
     
     
     
    	 System.out.println("\n\nMedian is " +median);  
    	}
     
     
    }
     
    Exception in thread "main" java.lang.NullPointerException
    	at media.main(media.java:26)


  2. #2
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: nullpointerexception bug

    Wrap your code in code tags. Post the exact error message you get.

  3. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: nullpointerexception bug

    Wait to define the a[] array until you know how many elements it should have. Something like:
            System.out.println("Enter the number of items\n");                  
            try {
                n=Integer.parseInt(br.readLine());
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
     
            // define the array here with the appropriate number of elements
            int[] a = new int[n];
     
            System.out.println("Input values \n");

  4. #4
    Junior Member
    Join Date
    Jul 2013
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: nullpointerexception bug

    The output after modifcation as u suggested is:
    plx see it nd suggest me
    [highlight=code]
    Enter the number of items

    4
    Input values

    1
    2
    3
    4

    java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unk nown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at media.main(media.java:27)
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at media.main(media.java:44)
    [\highlight]

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: nullpointerexception bug

    The error, "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at media.main(media.java:44)" points at this code:
            /* Sorting begins */
            for ( i = 1 ; i <= n-1 ; i++ )
            {     /* Trip-i begins  */
                for ( j = 1 ; j <= n-i ; j++ )
                {
                     /* Interchanging values */
                    if ( a[j] <= a[j + 1] )                              
                    {


    So you need to check the limits of the for loops:
    For n = 4, i in the first for loop ranges from i = 1 to i = 3. In the second for loop, j ranges from j = 1 to j = 3. Then, in the last line of the code above, the if() statement, j = 3 could make the statement:

    a[3] <= a[4]

    but 4 is not a legal index of the array a[]. It's too large or "out of bounds."

    Tracing the logic as I've done above is a demonstration of how you should find and then fix errors yourself. But when you need help, ask.

  6. The Following User Says Thank You to GregBrannon For This Useful Post:

    Jedi khan (July 11th, 2013)

  7. #6
    Junior Member
    Join Date
    Jul 2013
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: nullpointerexception bug

    I've tried another approach to find the median but am getting correct ans for odd case not the desired one in case of even. plz have a glance at it .i have just simply used statistics median formula.
    thanks alot in advance

    [highlight=java]
    import java.io.*;
    import java.util.Arrays;

    public class media {
    public static float findMedian(int array[]) {
    int i=0;
    int length=array.length;
    int[] sort = new int[length];
    System.arraycopy(array, 0, sort, 0, sort.length);
    Arrays.sort(sort);
    for(i=0;i<sort.length;i++)
    {
    System.out.println("Sorted array" +sort[i]);

    }
    if (length % 2 == 0) {

    return (sort[(sort.length / 2) - 1] + sort[(sort.length) / 2] / 2);
    }
    else {

    return sort[sort.length / 2];
    }
    }

    public static void main(String[] args) {

    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    int n=0;
    int i=0;
    System.out.println("Enter the no.of elements\n");
    try {
    n=Integer.parseInt(br.readLine());
    } catch (NumberFormatException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    int[] ranNum = new int[n];
    System.out.println("Input elements\n");
    for(i=0;i<n;i++)
    {
    try {
    ranNum[i]=Integer.parseInt(br.readLine());
    } catch (NumberFormatException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    float median=findMedian(ranNum);
    System.out.println("Median= "+median);
    }
    }


    [\highlight]

  8. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: nullpointerexception bug

    You just need to work through this formula to see if it is correct:

    return (sort[(sort.length / 2) - 1] + sort[(sort.length) / 2] / 2)

    So, for an even number of elements in the array, say '6', compute the formula's result:

    sort.length = 6:
    return (sort[(6 / 2) - 1] + sort[(6) / 2] / 2)
    = return (sort[(3) - 1] + sort[3] / 2)
    = return (sort[2] + sort[3] / 2)

    Which isn't quite what you want, I think. How can you fix the original equation to resolve to the desired return?

  9. The Following User Says Thank You to GregBrannon For This Useful Post:

    Jedi khan (July 11th, 2013)

  10. #8
    Junior Member
    Join Date
    Jul 2013
    Posts
    14
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: nullpointerexception bug

    plx do fix it for me

Similar Threads

  1. opacity bug? or just my code
    By xchan in forum AWT / Java Swing
    Replies: 1
    Last Post: April 22nd, 2013, 11:28 PM
  2. [SOLVED] Cant find stupid bug.
    By Saintroi in forum What's Wrong With My Code?
    Replies: 28
    Last Post: April 17th, 2012, 07:39 PM
  3. What's the bug in this code?
    By r3dApple in forum What's Wrong With My Code?
    Replies: 4
    Last Post: January 11th, 2012, 12:28 AM
  4. KeyListener bug
    By nivangerow in forum AWT / Java Swing
    Replies: 1
    Last Post: September 5th, 2011, 06:10 AM
  5. Apparent bug?
    By 342-173=147 in forum Loops & Control Statements
    Replies: 2
    Last Post: March 4th, 2011, 02:52 PM