简单错误(While循环)帮助在我的Java Palindrome计划中

时间:2015-12-06 03:35:14

标签: java palindrome

我正在用Java构建一个回文程序。分配是从文件中读取单词,确定文件中的单词是否是回文,并将结果发送到另一个文件。我有一切正常,但我的程序中唯一的问题是它只会读取第一个单词。我需要它来读取文件中的所有行。我的代码是:

import java.util.Scanner;
import java.io.*;

public class str1 {

    public static void main(String args[]) {
      try {

      String reverse = "";
      System.out.print("Enter the name of the input file: ");
      Scanner keyboard = new Scanner(System.in);
      String a = keyboard.nextLine();
      int length = a.length();
      File inFile = new File(a);
      Scanner fin = new Scanner(inFile);
      System.out.print("Enter name of the output file: ");
      String outFileName= keyboard.nextLine();
      File outFile = new File(outFileName);
      PrintWriter fout = new PrintWriter(outFile);
      while ( fin.hasNext(a) ) {
      for ( int i = length - 1; i >= 0; i-- )
     reverse = reverse + a.charAt(i);

  if (a.equals(reverse))
     fout.println("Entered string is a palindrome.");
  else
     fout.println("Entered string is not a palindrome.");
      }
      fin.close();
      fout.close();
      System.out.print("Done. See '" + outFileName + "'.");
      } catch (Exception e) {
          e.printStackTrace();
      }
    }
}

我试图将第23行中的while更改为“while(fin.hasNextLine(a)){”但我没有成功。我相信这就是为什么它不会读过第一行。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

这应该有效。您需要在检查输入文件的条件后添加h_vertices方法,实际处理它,并在读取后检查单词的长度:

import java.io.File; import java.io.PrintWriter; import java.util.Scanner;

nextLine

答案 1 :(得分:0)

@QQ_At_The_PewPew,你犯了一个错误,你正在对String" a"这是您的文件名,而不是您从文件中输入的文件。

import java.util.Scanner;
import java.io.*;

public class str1 {

    public static void main(String args[]) {
      try {

      String reverse = "";
      System.out.print("Enter the name of the input file: ");
      Scanner keyboard = new Scanner(System.in);
      String a = keyboard.nextLine();
      int length = a.length();
      File inFile = new File(a);
      Scanner fin = new Scanner(inFile);
      System.out.print("Enter name of the output file: ");
      String outFileName= keyboard.nextLine();
      File outFile = new File(outFileName);
      PrintWriter fout = new PrintWriter(outFile);
      while ( fin.hasNext() ) {
      String s=fin.nextLine();
      for ( int i = length - 1; i >= 0; i-- )
     reverse = reverse + s.charAt(i);

  if (s.equals(reverse))
     fout.println("Entered string is a palindrome.");
  else
     fout.println("Entered string is not a palindrome.");
      }
      fin.close();
      fout.close();
      System.out.print("Done. See '" + outFileName + "'.");
      } catch (Exception e) {
          e.printStackTrace();
      }
    }
}