In: Computer Science
SAMPLE PROGRAM RUN #1
Enter a word: carrot
First half: car
Second half: rot
SAMPLE PROGRAM RUN #2
Enter a word: plant
First half: pl
Second half: ant
Complete your answer by typing code below
import java.util.Scanner;
public class WordHalves
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = reader.nextLine();
}
}
OUTPUT :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = reader.nextLine();
// word.length() returns length of the string
int length = word.length();
// mid - the middle value
int mid = length/2;
// obtaining first half and second half using substring
String first_half = word.substring(0,mid);
String second_half = word.substring(mid);
System.out.println("First half : "+first_half);
System.out.println("Second half : "+second_half);
}
}
OUTPUT: