Anzeige
Please use Java to code the program- thank you! Write a program that a.docx
Please use Java to code the program- thank you! Write a program that a.docx
Please use Java to code the program- thank you! Write a program that a.docx
Nächste SlideShare
Ch09Ch09
Wird geladen in ... 3
1 von 3
Anzeige

Más contenido relacionado

Más de rtodd884(20)

Anzeige

Please use Java to code the program- thank you! Write a program that a.docx

  1. Please use Java to code the program, thank you! Write a program that asks the user to enter a sentence. The program then passes the String into a method called convertString that changes the String to an array of chars and returns the array. The program then passes the array into a method called isReverse and returns true/false if the array of chars is a palindrome. Ignore whitespace and punctuation (space, tab, single quote, double quote, exclamation, comma, question mark, hyphen, semi-colon, colon, period). Ignore case as well. For example, all these inputs are palindromes: A man, a plan, a canal, panama. Was it a car or a cat I saw?"If I had a hi-fi!!" Use the following template: import java.util.Scanner; Solution Given below is the code for the question with output. Hope it helps. If it did, please do rate the answer . Thank you very much import java.util.Scanner; public class Ex1 { public static void main(String[] args) { Scanner keybd = new Scanner(System.in); System.out.println("Enter a sentence: "); String sentence = keybd.nextLine(); char[] arr = convertString(sentence); if(isReverse(arr)) System.out.println(sentence + " is a palindrome"); else System.out.println(sentence + " is NOT a palindrome"); } //convert the input string into lower case and returns the array public static char[] convertString(String s) { char[] arr = new char[s.length()]; for(int i = 0; i < s.length(); i++) { char ch = s.charAt(i);
  2. if(ch >= 'a' && ch <= 'z') //lower case .. no change arr[i] = ch; else if(ch >= 'A' && ch <= 'Z') //is it upper case ? change to lower arr[i] = (char) (ch - 'A' + 'a'); else //other characters no change arr[i] = ch; } return arr; } //input is array of lower case letters and other special characters public static boolean isReverse(char[] arr) { int i = 0; int len = arr.length; int j = arr.length - 1; char ch1, ch2; while(i < len && j >= 0) { //skip from left to right any non alphbetci characters, get the 1st letter from left //to be matched. do { ch1 = arr[i++]; }while(i < len && (ch1 < 'a' || ch1 > 'z')); //skip from right to left any non alphabetic characters, get the 1st letter from left //to be matched.s do { ch2 = arr[j--]; }while(j >= 0 && (ch2 < 'a' || ch2 > 'z')); if(ch1 != ch2) return false; } return true; } } output Enter a sentence: was it a car was it a car is NOT a palindrome Enter a sentence:
  3. Was it a car OR A CAT I SAW?? Was it a car OR A CAT I SAW?? is a palindrome
Anzeige