java - 轻松修复第二次无法正确执行的 while 循环?
问题描述
我是java的新手,目前的任务是取一个给定的单词,将第一个单词放在最后,从反向重建单词,看看它是否与原来的单词相同,例如:语法,土豆,不均匀,梳妆台,香蕉等。到目前为止,我有这个:
Scanner input = new Scanner(System.in);
String original, reverse = "";
String exit = "quit";
int index;
System.out.println("Please enter a word (enter quit to exit the program): ");
original = input.next();
while (!original.equalsIgnoreCase(exit))
{
String endingChar = original.substring(0, 1);
String addingPhrase = original.substring(1);
reverse += endingChar;
for (index = addingPhrase.length() - 1; index >= 0; --index)
{
char ch = addingPhrase.charAt(index);
reverse += ch;
}
if (original.equals(reverse))
{
System.out.println("Success! The word you entered does have the gramatic property.");
}
else
{
System.out.println("The word you entered does not have the gramatic property."
+ " Please try again with another word (enter quit to exit the program): ");
}
original = input.next();
}
input.close();
当我运行它并输入单词“banana”时,它正确地识别出当 b 移动到末尾时它确实是向后的,并且对上面列出的其他单词也是如此,但是当我输入第二个单词时循环,它永远不会正确识别它,并且总是用 else 块中的 print 语句响应:
Please enter a word (enter quit to exit the program):
banana
Success! The word you entered does have the gramatic property.
banana
The word you entered does not have the gramatic property. Please try again
with another word (enter quit to exit the program):
我猜这与我制作 for 循环的方式或我在 while 循环结束时要求输入的方式有关,但就像我说的那样,我在调试方面相当新而且很糟糕。任何帮助将不胜感激,在此先感谢。
解决方案
您在每次迭代中都在更改字符串reverse
,但您并没有清除它。因此,在循环结束之前或开始时清除字符串,例如像这样:reverse = ""
,然后它应该没问题。
推荐阅读
- c++ - 编写一个程序来演示重载复制构造函数的技术?
- python - 带有 add_swig_library 的未定义符号
- angular - 消息:“SQLSTATE [HY000] [2002] php_network_getaddresses:getaddrinfo 失败:名称解析暂时失败(SQL:从 `users` 中选择 *...)”
- botframework - 使用消息传递端点注册 OAuth2 机器人
- linux - 为什么我必须使用 ld 来链接我的二进制文件
- c# - 加入两个对象列表,从第二个列表中获取第一个匹配对象
- angular - 角材料垂直步进器 | 在最后一步中延长垂直线
- html - 如何使 Bootstrap 4 Image Overlay 卡完全可点击?
- swift - 当 AVPlayer 在后台播放音频时 UI 冻结
- python - 将字符串数组与二维数组匹配