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 =;" 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.out.print("Enter string: ");
         String str =;
         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;

Open in new window

Who is Participating?
mccarlConnect With a Mentor IT 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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.