Middle.java.html

  1  import java.util.Scanner;
  2  
  3  public class Middle
  4  {
  5     public static void main(String[] args)
  6     {
  7        Scanner in = new Scanner(System.in);
  8  
  9        System.out.print("Enter a string: ");
 10        String str = in.next();
 11  
 12        int position;
 13        int length;
 14        if (str.length() % 2 == 1)
 15        {
 16           position = str.length() / 2;
 17           length = 1;
 18        }
 19        else
 20        {
 21           position = str.length() / 2 - 1;
 22           length = 2;
 23        }
 24        String result = str.substring(position, position + length);
 25  
 26        System.out.println("Middle: " + result);
 27     }
 28  }