Java Help

Here is the problem..
Write a method
public static String middle(String str)
that returns a string containing the middle character in str if the length of str is odd, or the two middle characters if the length is even. For example, middle("middle") returns "dd". I need help with the "String str = in.next();" part.

Here is what I have

package p.pkg5_4;
import java.util.Scanner;
/**
 *
 * @author toddrastall
 */
public class P5_4 {

    /**
     * @param args the command line arguments
     */
        public static String middle(String str){
         Scanner in = new Scanner(System.in);
         System.out.print("Enter string: ");
         String str = in.next();
      
         if ((str.length() % 2) == 0)
         {
            if (str.length() > 2)
           {
               return str.substring( str.length() / 2 - 1, str.length() / 2 +1);
           } 
         }        
            return str.substring(str.length() / 2, str.length() / 2 + 1 );
      }
      public static void main(String[] args)
    {
            String str = null;
         System.out.print(middle(str));
    }
}

Open in new window

TheChosAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
The problem is that you are already passing the String that should be examined INTO your "middle()" method, so you don't need to then get an input string from the user, inside that method.

I am asumming that this may be a homework type question, so I can only give you a general hint. That is to move the first three lines from your middle() method (ie. lines 13,14,15 from above) out of the middle() method. You possibly could put these lines in your main() method though if you want the user to have to enter the string to be worked on.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.