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 2 of 2

Thread: if...else

  1. #1
    Junior Member
    Join Date
    Oct 2009
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default if...else

    Hello to all,

     public Person elementAt(int index)
        {  
        	if (maxSize < index)
        	{
        		System.out.println("Wrong Index");
        		System.out.println("PLease Insert A Value From 0 To "+ maxSize);
        	}
        	else
        		return list[index];
     
        }

    On this code, an error appears keeps saying that this method must return a value.
    If I just add another return after the existing one…then works
    Any ideas?
    Thank you in advanced!!


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: if...else

    Your conditional if (maxSize < index) is not returning anything. You can fix the compiling error by returning null, but if you do it this way you must safeguard any code that uses this function to make sure a nullpointerexception isn't thrown.
     public Person elementAt(int index)
        {  
        	if (maxSize < index)
        	{
        		System.out.println("Wrong Index");
        		System.out.println("PLease Insert A Value From 0 To "+ maxSize);
                    return null;
        	}
        	else
            {
        		return list[index];
            }
     
        }