[英]Java, Program to check if a string is a palindrome
I have a Java Assignment where I have to prompt for a line input, check if its a palindrome and then say if the palindrome is made of all text, all numbers, or mixed. 我有一个Java作业,必须提示输入行,检查其回文,然后说回文是由所有文本,所有数字还是混合字母组成的。 I haven't added the part where I check what kind of palindrome it is yet, but I need help with the code to check if it's a palindrome.
我还没有添加检查回文类型的部分,但是我需要代码帮助以检查它是否是回文。 The code I posted below recognizes everything as a palindrome even if it isn't.
我在下面发布的代码将所有内容都视为回文,即使不是这样。 This is basic Java so I'm limited to what I used below.
这是基本的Java,因此仅限于以下内容。
import java.util.Scanner;
public class Project4{
public static void main (String [] args)
{
String line = getInputLine();
while (!isEmptyLine (line))
{
if (isPalindrome (line))
System.out.println ("\"" + line + "\" is a palindrome.");
else
System.out.println ("\"" + line + "\" is not a palindrome");
line = getInputLine();
}
System.out.println ("End of program");
}
public static String getInputLine ( )
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a line of input: ");
String inputline = in.nextLine();
return inputline;
}
public static boolean isEmptyLine(String str)
{
boolean truefalse;
if(str.length()==0)
truefalse = true;
else
truefalse = false;
return truefalse;
}
public static boolean isPalindrome(String str)
{
int left = 0;
int right = str.length();
boolean okay = true;
char ch1; char ch2;
while(okay && left<right)
{
ch1 = str.charAt(left);
if(!Character.isDigit(ch1)||!Character.isLetter(ch1))
left++;
else
{
ch2 = str.charAt(right);
if(!Character.isDigit(ch2)||!Character.isLetter(ch2))
right--;
else
{
ch1 = Character.toUpperCase(ch1);
ch2 = Character.toUpperCase(ch2);
if(ch1==ch2)
{
left++;
right--;
}
else
okay = false;
}
}
}
return okay;
}
}
您需要对2个检查进行逻辑AND运算,而不是OR-
if(!Character.isDigit(ch1) && !Character.isLetter(ch1))
Use a method like the following: 使用如下方法:
boolean isPalindrome (String input) {
int strLength = input.length;
for (int i=0; i < input.length/2; ++i) {
if (input.charAt(i) != input.charAt(strLength-i)) {
return false;
}
}
return true;
}
A late answer although it might help some in the future. 答案较晚,尽管将来可能会有所帮助。 The method posted below doesn't use any of StringBuilder functions.
下面发布的方法不使用任何StringBuilder函数。
public boolean isPalindrome(String value) {
boolean isPalindrome = true;
for (int i = 0 , j = value.length() - 1 ; i < j ; i ++ , j --) {
if (value.charAt(i) != value.charAt(j)) {
isPalindrome = false;
}
}
return isPalindrome;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.