该程序旨在查找用户输入是否为回文结构。但是在isPalindrome方法中,我一直得到规定的错误。当我修复它时,我得到24个错误,说它找不到多个其他变量。请帮忙。
以下是代码:
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 and a " + getPalType (line));
else
System.out.println ("\"" + line +
"\" is not a palindrome");
line = getInputLine();
}
System.out.println ("End of prgram");
}
public static String getInputLine () //Ask user for input and then returns the line
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter your possible Palindrome: ");
String getInputLine = scan.nextLine();
return getInputLine;
}
public static boolean isEmptyLine (String str) // Return TRUE if the paramater is empty or False otherwise
{
if (line != null)
{
isEmptyLine = true;
}
else
{
isEmptyLine = false;
}
}
public static boolean isPalindrome (String str)// Return TRUE if the str is a palindrome or FALSE otherwise
{
int left = 0;
int right = line.length() - 1;
boolean okay = true;
while (okay && left < right){
char ch1 = line.charAt(left);
if (!(Character.isDigit(ch1) || Character.isLetter(ch1))){
left ++;
else{
ch2 = line.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;
}
public static String getPalType (String str)//Determine the type of the palindrome and return either word/phrase/number.
{
int num = 0;
int let = 0;
int length = line.length();
for (int i = 0; i <= length; i++)
{
if (Character.isDigit(line.charAt(i)))
num++;
else if (Character.isLetter(line.charAt(i)))
let++;
}
if (num > 0 && let == 0)
{
getPalType = number;
return getPalType;
}
else if (let > 0 && num == 0)
{
getPalType = word;
return getPalType;
}
else
getPalType = phrase;
return getPalType;
}
}
答案 0 :(得分:0)
错过了
的最佳起始位置 if (isPalindrome (line))
如果您有一个或另一个,则不能使用结束一行样式。只需添加开始括号即可。
需要这样:
while (!isEmptyLine (line)) {
if (isPalindrome (line)){
System.out.println ("\"" + line +
"\" is a palindrome and a " + getPalType (line));
}else{
System.out.println ("\"" + line +
"\" is not a palindrome");
line = getInputLine();
} //since you have two lines not one in the else.
}
System.out.println ("End of prgram");