[英]Java Palindrome program (1 error)
我昨天問了一個關於回文和 Java 的問題:
到目前為止,在您的幫助下,我已經取得了一些進展(再次非常感謝您)。 在我可以測試代碼之前,我只需要另外一件事的幫助。 我正在使用 Eclipse,但在一行中出現錯誤(我還將將該錯誤作為注釋包含在下面的代碼中)。 .我不斷收到 。
有誰知道這里發生了什么? 我已經有一段時間沒有使用 Java 了。 大約 12 個月前在 CS One 中使用它,然后我在數據結構中轉到 C++,然后在下一門課程中轉到機器代碼和匯編語言。 這是代碼(我還在代碼的注釋中包含了錯誤)。 非常感謝:
public class Palindrome
{
public boolean isPalindrome( String theWord )
{
for ( int i = 0; i < theWord.length( ); i++ ) {
if ( theWord.charAt(i) != theWord.charAt (theWord.length() - i - 1) ) {
return false;
}
}
return true;
}
public static void main( String [] theWord )
{
int leftPointer = 0;
int rightPointer = theWord.length - 1;
for ( int i = 0; i < theWord.length / 2; i++ ) {
while (leftPointer >= rightPointer) {
if ( theWord.charAt(i) == theWord.charAt (theWord.length - i - 1) ) { // Error: Cannot invoke charAt(int) on the array type String[]
leftPointer++;
rightPointer--;
}
System.out.println(theWord);
}
}
}
}
您正在嘗試訪問 String[](傳遞給程序的參數的 String 數組)上的 charAt(),但您需要在 String 上訪問它。 我的世界建議如下:
if ( theWord[i].charAt(0) == theWord[theWord.length - i - 1].charAt (0) ) {
那可能對你有幫助。
charAt(int index) 應用於字符串,而不是字符串數組。 你的程序想要判斷一個字符串是否是回文,比如“abcba”。 而不是檢查字符串數組是否都是回文,對嗎? 例如 {"abcba", "bbc", "aba"}。
您在調用方法 .length() 后忘記了 ()
在 Java 中(如在 C++ 中)程序接收參數列表,它是字符串數組。 因此,您的課程應如下所示:
public class Palindrome
{
public static boolean isPalindrome( String theWord )
{
for ( int i = 0; i < theWord.length( ); i++ ) {
if ( theWord.charAt(i) != theWord.charAt (theWord.length() - i - 1) ) {
return false;
}
}
return true;
}
public static void main( String [] args )
{
String theWord = args[0]; // first word passed to the program
boolean isPalindrom = Palindrome.isPalindrome(theWord);
System.out.println(theWord + " is" + ( isPalindrom ? "" : " NOT " ) + " a Palindrome." );
}
}
public static boolean isPalindrom(String value) {
if (value == null || value.length()==0 || value.length()==1) {
return true;
}
if(value.charAt(0)!=value.charAt(value.length()-1)) {
return false;
}
StringBuilder newValue =new StringBuilder(value);
newValue = new StringBuilder(newValue.substring(1, newValue.length()));
newValue = new StringBuilder(newValue.substring(0, newValue.length()-1));
return isPalindrom(newValue.toString());
}
試試這個簡單的遞歸方法。
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String str = "pappap";
String sp = str.toLowerCase();
char[] ch = sp.toCharArray();
int len = ch.length;
int lastIndex = ch.length-1;
int count = 1;
int first = 0;
int last = sp.length()-1;
for(; first < last ;){
if(ch[first] == ch[last] ){
first= first+1;
last= last-1;
}
else{
count = 0;
break;
}
}
String result = (count == 1) ? "Palindrome" : "Not a palindrome " ;
System.out.println(result);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.