java - 单词生成器中无限循环文本的问题
问题描述
我正在制作一个回文发生器。基本上,用户输入一个单词或句子,程序输出它是否是回文,这是一个正向和反向拼写相同的单词,如“wow”或“racecar”。我的程序运行良好,但是输出文本会重复 50 次,我似乎无法弄清楚问题出在哪里,而不会把所有事情都搞砸。帮助将不胜感激。
import javax.swing.JOptionPane;
public class palindromedectector {
public static void main(String[] args) {
String testStrings = "";
testStrings = JOptionPane.showInputDialog("Enter word: ");
for (int i = 0; i < testStrings.length(); i++)
{
System.out.print("\"" + testStrings + "\"");
if (isPalindrome(stripString(testStrings)))
System.out.println(" is a palindrome.");
else
System.out.println(" is not a palindrome.");
}
}
public static String stripString(String strip)
{
strip = strip.toUpperCase();
String stripped= "";
for (int i= 0; i< strip.length(); i++)
{
if (Character.isLetter(strip.charAt(i)))
stripped += strip.charAt(i);
}
return stripped;
}
public static boolean isPalindrome (String str)
{
boolean status = false;
if (str.length() <= 1)
status = true;
else if (str.charAt(0) == str.charAt(str.length()-1))
{
status = isPalindrome (str.substring(1, str.length()-1));
}
return status;
}
}
解决方案
主要问题是您isPalindrome
在循环中运行检查相同的字符串,可能您想运行多个检查
public static void main(String[] args) {
final int attempts = 5;
for (int i = 0; i < attempts; i++) {
String word = JOptionPane.showInputDialog("Enter word: ");
System.out.print("\"" + word + "\"");
if (isPalindrome(stripString(word))) {
System.out.println(" is a palindrome.");
} else {
System.out.println(" is not a palindrome.");
}
}
}
此外,主要功能可以以更短的方式实现:
// use regexp to get rid of non-letters
private static String stripString(String word) {
if (null == word || word.isEmpty()) {
return word;
}
return word.replaceAll("[^A-Za-z]", "").toUpperCase(); // remove all non-letters
}
// use Java Stream API to check letters using half of word length
private static boolean isPalindrome(String word) {
if (null == word) {
return false;
}
final int len = word.length();
if (len < 2) {
return true;
}
return IntStream.range(0, len/2)
.allMatch(i -> word.charAt(i) == word.charAt(len - 1 - i));
}
推荐阅读
- javascript - 用百分比计算器创建一个整数
- sql - 如何将亚马逊卖家报告上传到 SQL 数据库?
- python - 将量化的 Pytorch 模型导出到 onnx 时出现分段错误
- android - 在特定时间关闭 App 时安排 Android 功能
- f# - 任何地方都有 option<> 计算表达式吗?
- python - 最大子数组总和 - 我的解决方案哪里错了?Kadane 算法
- c# - Google API Explorer 不会创建 Compute Engine 虚拟机实例
- java - junit 5 自定义参数化测试
- palantir-foundry - 如何获得轮廓中多列的最小值?
- apache - 在 httpd.conf 中加载模块 mod_proxy_cluster.so 时,在 AIX 7.2 powerpc v1.3.0 上出现以下错误))