2016-09-08 22 views
0

目前我正在试图用Java编写回文检查是不区分大小写。 我检查了其他主题,但没有一个似乎解决了我的问题。Java的回文检查 - 不区分大小写

这里是我的代码:

import java.util.Scanner; 

public class Homework5_2 { 
    public static void main(String[] args) { 
     boolean flag = true; //palindrome or not 
     Scanner console = new Scanner(System.in); 
     System.out.print("Enter one or more words: "); 
     String s = console.next(); 

     //checks if string contains spaces 
     if (s.matches(".*\\s+.*")) { 
      s = s.replaceAll("\\s+",""); 
     } 

     s = s.toLowerCase(); 
     int stringLength = s.length(); 
     int index = 0; 

     //checks the string from both sides going towards the middle 
     for (int i=0;i<stringLength/2;i++) { 
     index = stringLength-i-1; 
     if (!(s.charAt(i) == s.charAt(index))) { 
      flag = false; 
      } 
     } 

     if (flag == true) { 
      System.out.println("The string is a palindrome!"); 
     } else { 
      System.out.println("The string is not a palindrome!"); 
     } 
    } 
} 

当进入像“操作系统,所以”,不正确的输出字符串,因为该字符串不是回文报道。 该问题似乎与空格有关,因为如果其中没有空格,则相同的字符串会正确报告为回文。 我真的有兴趣了解这段代码的缺陷,任何帮助将非常感谢!

回答

2

使用console.nextLine()代替console.next()

默认情况下,console.next()仅收集下一个由空格分隔的标记,因此当您输入“Os SO”时,它实际上只在String s变量中存储“Os”。

在检查回文而言,它是非常容易扭转串并检查是否反转字符串等于原来的,而不是使用索引来检查字符串中的每个个性。

0

这是我对这个问题的解决方案:

import java.util.Scanner; 

public class CheckPalindrome { 

    public static void main(String[] args) { 
     Scanner console = new Scanner(System.in); 
     String userInput = ""; 
     String auxiliar = ""; 

     userInput = console.nextLine(); 
     auxiliar = new StringBuilder(userInput).reverse().toString(); 

     if (userInput.equalsIgnoreCase(auxiliar)) { 
      System.out.println("This string is a palindrome"); 
     } else { 
      System.out.println("This string is not a palindrome"); 
     } 

     console.close(); 
    } 
}