A palindrome is a string that reads the same forward and backward. Write a program
that reads a string from the keyboard and tells the user if the string is a palindrome.
import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
String input;// user input
int i;// iteration
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a word: ");// prompt user
input = keyboard.next();
int length = input.length();// get length
for (i = 0; i < (length / 2); i++) {// loop through first half of word
if (!(input.charAt(i) == input.charAt(length - 1 - i)))// check if corresponding characters match
{
System.out.println(input + " is not a palindrome.");
break;
}
}
if (i == length / 2)
System.out.println(input + " is a palindrome.");
keyboard.close();
}
}
No comments:
Post a Comment