我的任务是通过读取自己创建的文本文件来创建数组。概念中的程序应该读取我输入的单词,并将它们存储在数组中。接下来,我将创建一个递归方法来检查并查看每行是否是回文并打印结果。目前,我收到堆栈溢出错误。抱歉,如果代码没有太多注释。
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 Palindromen");
}
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");
}
}
}
在对 FindPalindrome
方法的递归调用中,您传递的是从未使用的字符串,因为 FindPalindrome
方法会查看原始字符串数组中的第一个条目并忽略其参数。 因此,它只是使用相同的参数反复调用自己,直到溢出堆栈。
你引用Palindromes[i]
FindPalindrome
的任何地方,你都应该引用参数FoundPalindrome
,然后它实际上可能会起作用。