String Play (JAVA BEGINNER) Implement the following methods: // Write a method t
ID: 3873154 • Letter: S
Question
String Play (JAVA BEGINNER)
Implement the following methods:
// Write a method that returns true if s has leading or trailing whitespace, false otherwise
public static boolean needsTrim(String s)
// Write a method that swaps the first three and last four characters of s
public static String swap3For4(String s)
// Write a method that has one String parameter, and returns true if the first half and last half of the parameter are the same ignoring case, and false otherwise. (The name of the method is up to you.)
Use these methods to rewrite the corresponding parts of the attached StringPlay program.
Explanation / Answer
StringPlay.java
import java.util.Scanner;
public class StringPlay {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a line of text: ");
String aLine = kybd.nextLine();
if (needsTrim(aLine)) {
System.out
.println("The original string has no leading or trailing whitespaces");
} else {
System.out
.println("The original string has leading or trailing whitespaces");
}
System.out.println("First 3 and last 4 chars swapped: "+swap3For4(aLine));
System.out.println("Does the first half equal the last half? "+isSame(aLine));
}
public static boolean isSame(String s) {
int midPoint = s.length()/2;
String firstHalf = s.substring(0, midPoint);
if(s.length() % 2 == 1) midPoint++;
String secondHalf = s.substring(midPoint);
return firstHalf.equalsIgnoreCase(secondHalf);
}
public static String swap3For4(String s) {
String swapped = s.substring(s.length() - 4)
+ s.substring(3, s.length() - 4) + s.substring(0, 3);
return swapped;
}
public static boolean needsTrim(String s) {
if (s.trim().equals(s)) {
return true;
}
return false;
}
}
Output:
Enter a line of text:
Morning
The original string has leading or trailing whitespaces
First 3 and last 4 chars swapped: ningMor
Does the first half equal the last half? false