📄 palindrometest.java
字号:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class PalindromeTest {
private boolean flag = false;
public PalindromeTest()
{
}
//loop compare method
public boolean Iterrative(String str)
{
for (int i = 0; i < str.length()/2; i++)//loop entry condition
{
if (str.charAt(i) != str.charAt(str.length() - i - 1))
{ //use charAt method to compare
return false;
}
}
return true;
}
//makes calls to itself
public boolean Recursive(String str) //the Recursive method
{
if (str.length() == 1) // must be a palindrome
{
this.flag = true;
}
else
{
if(str.substring(0,1).equals(
str.substring(str.length()-1, str.length())))
{ //check each two character from the first and the last
String temp = str.substring(1, str.length()-1);
if(temp.length() > 0)
{
this.flag = true;
Recursive(temp);
}
}
else
{
this.flag = false;
}
}
return this.flag;
}
public static void main(String[] args) throws IOException {
//Declaration
BufferedReader input = new BufferedReader
(new InputStreamReader(System.in));
String inputLine;
PalindromeTest pt = new PalindromeTest();
System.out.print("Please input a line of text: ");
inputLine = input.readLine();
inputLine = inputLine.toLowerCase();
while(inputLine.length() > 0)
{
//
//handle spaces and punctuation marks
//
//use regular expressions
Pattern p = Pattern.compile("[.,\"\\?!:;<>']");//punctuation marks
Matcher m = p.matcher(inputLine);
String first = m.replaceAll("");//replace all punctuation marks
p = Pattern.compile("\\s");
m = p.matcher(first);
String second = m.replaceAll("");//replace spaces
inputLine = second;
if(inputLine.length() > 0)
{
//call two different methods to check
if(pt.Iterrative(inputLine))
{
System.out.println("Iterative version: This is a palindrome!");
}
else
{
System.out.println("Iterative version: This is not a palindrome!");
}
if(pt.Recursive(inputLine))
{
System.out.println("Recursive version: This is a palindrome!");
}
else
{
System.out.println("Recursive version: This is not a palindrome!");
}
}
else
{
System.out.println("All you input are punctuation and space!");
}
System.out.println("");
System.out.print("Please input a line of text: ");
inputLine = input.readLine();
inputLine = inputLine.toLowerCase();
}
if(inputLine.length() == 0) //if blank line
{
System.out.println("Program terminated!");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -