我的任务是通过读取我自己创建的文本文件来创建数组。概念中的程序应该读取我输入的单词,并将它们存储在一个数组中。接下来,我将创建一个递归方法来检查并查看每一行是否为回文并打印结果。目前,我收到了堆栈溢出错误。对不起,如果代码没有评论太多。
package palindrome;
import java.util.*;
import java.io.*;
/**
*
* @author alexanderrivera
*/
public class Palindrome {
// Static variables can be used in ALL instances of a class
public static String [] Palindromes;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// Establishes a value to Palindromes
Palindromes = new String[10];
int i=0;
// calls the readFile method to read the file
readFile("Palindrome.txt");
FindPalindrome(Palindromes[i]);
}// end of main method
// begining of the readFile method
public static void readFile(String fileName)
{
// sets the int variable to zero
int i = 0;
// establishes the java input for reading the file
java.io.File inputFile = new java.io.File(fileName);
// being try catch block
try{
// establishes instance of the scanner to read the file
Scanner fileReader = new Scanner(inputFile);
// being while statement
while(fileReader.hasNextLine())
{
Palindromes[i] = fileReader.nextLine();
i++;
}// end while statement
// closes the file reader
fileReader.close();
// print the index to see if it was read
}catch (FileNotFoundException e){
System.out.println("Sorry, cannot find the file");
}// end error message
} // end the method
public static void FindPalindrome(String FoundPalindrome) {
int i=0;
{
if (Palindromes[i].length() == 0 || Palindromes[i].length() == 1) {
System.out.println(Palindromes[i] + " This is a Palindrome\n");
}
if (Palindromes[i].charAt(0) == Palindromes[i].charAt(Palindromes[i].length() - 1)) {
FindPalindrome(Palindromes[i].substring(1, Palindromes[i].length() - 1));
}
// otherwise
System.out.println("This is not a Palindrome \n");
}
}
}
答案 0 :(得分:2)
在对FindPalindrome
方法的递归调用中,您传递的是从未使用过的字符串,因为FindPalindrome
方法会查看原始字符串数组中的第一个条目并忽略其参数。所以它只是用相同的参数重复调用自己,直到它溢出堆栈。
您引用FindPalindrome
的{{1}}中的任何地方,您应该引用参数Palindromes[i]
,然后它实际上可以正常工作。