2

我正在创建一个程序来检查单词或短语是否是回文。我已经弄清楚了实际的“回文测试仪”。我坚持的是在我的代码中放置的位置和内容让控制台读出“输入回文......”然后文本。我已经尝试过使用 IO,但效果不佳。另外,我如何创建一个循环来继续前进?此代码一次只允许一个 `public class Palindrome {

public static void main(String args[]) {  
  String s="";  
  int i;  
  int n=s.length(); 
  String str="";  

  for(i=n-1;i>=0;i--)  
   str=str+s.charAt(i);  

  if(str.equals(s))  
   System.out.println(s+ " is a palindrome");  

  else  System.out.println(s+ " is not a palindrome"); }

}
4

3 回答 3

7

要阅读文本,您需要使用 Scanner 类,例如:

import java.util.*;

public class MyConsoleInput {

    public static void main(String[] args) {
        String myInput;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter some data: ");
        myInput = in.nextLine();
        in.close();

        System.out.println("You entered: " + myInput);
    }
}

在你实际进行回文检查之前应用这个概念,你就会在这方面进行排序。

至于循环允许多次检查,您可以执行诸如提供关键字(例如“exit”)之类的操作,然后执行以下操作:

do {
    //...
} while (!myInput.equals("exit"));

显然,您的相关代码在中间。

于 2010-04-17T01:39:20.783 回答
1

不是一个真正的答案,因为它已经给出(因此 CW),但我无法抗拒(重新)编写该isPalindrome()方法;)

public static boolean isPalindrome(String s) {
    return new StringBuilder(s).reverse().toString().equals(s);
}
于 2010-04-17T03:42:57.123 回答
0

另一个常见的习惯用法是将测试包装在一个方法中:

private static boolean isPalindrome(String s) {
    ...
    return str.equals(s);
}

然后过滤标准输入,isPalindrome()为每一行调用:

public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String s;
    while ((s = in.readLine()) != null) {
        System.out.println(isPalindrome(s) + ": " + s );
    }
}

这使得检查单行变得容易:

回声“夫人” | java我的类

或整个文件:

java MyClass < /usr/share/dict/words
于 2010-04-17T03:25:19.707 回答