Problem:
Write a class StringManipulation that contains one instance variable stringValue with the corresponding setter and getter methods. Your constructor should allow the user to initialize the value of stringValue. Inside the class, you will include two methods; The first method isPalindome(), will return true if the string is equivalent when read from left to right or from right to left. The second method, reverse() will return the string in reverse. In your tester class, StringManipulationTester, you will ask the user to input 2 strings and print if the string is a palindorme then print it in reverse.Output:
Please enter string 1 value:lol
The string is a palindrome
The string in reverse is lol
Please enter string 2 value:
wolf
The string is not a palindrome
The string in reverse is flow
Solution:
public class StringManipulation { private String word; public StringManipulation(String word) { this.word = word; } public String getWord(String word) { return word; } public void setWord(String word) { this.word = word; } public String isPalindrome() { boolean value = true; for(int i = 0; i < this.word.length() - 1; i++) { if(this.word.charAt(i) != this.word.charAt(this.word.length() - (i + 1))) { value = false; } } if (value == false) { return "The string is not a palindrome"; } else return "The string is a palindrome"; } public String reverse() { String S = ""; for (int count = word.length() - 1; count >= 0; count--) S +=word.charAt(count); return "The string reverse " + S; } }
import java.util.Scanner; public class StringManipulationTest { public static void main (String[] args) { Scanner scan = new Scanner (System.in); System.out.println("Please enter string 1 value:"); String string1 = scan.nextLine(); StringManipulation str1 = new StringManipulation(string1); System.out.println(str1.isPalindrome()); System.out.println(); System.out.println(str1.reverse()); System.out.println("Please enter string 2 value:"); String string2 = scan.nextLine(); StringManipulation str2 = new StringManipulation(string2); System.out.println(str2.isPalindrome()); System.out.println(); System.out.println(str2.reverse()); } }
No comments :
Post a Comment