Advertisement
CoineTre

JF-ExcMethods06.Middle Characters

Feb 12th, 2021
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.76 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Exc6MiddleCharacters {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.         String text = scanner.nextLine();
  7.         middleChar(text);
  8.     }
  9.  
  10.     private static void middleChar(String text) {
  11.         int input = text.length();
  12.         if (input % 2 == 1){
  13.             char ch = text.charAt(input/2);
  14.             System.out.println(ch);
  15.         }else {
  16.             char ch1 = text.charAt(input/2-1);
  17.             char ch2 = text.charAt(input/2);
  18.             System.out.printf("%c%c",ch1,ch2);
  19.         }
  20.     }
  21. }
  22.  
  23.  
  24. //You will receive a single string. Write a method that prints the middle character.
  25. // If the length of the string is even, there are two middle characters.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement