在 Java 中获取用户输入
我正在创建一个程序来检查单词或短语是否是回文。我已经弄清楚了实际的“回文测试器”。我所困扰的是在我的代码中放置什么位置和内容,以使控制台读出“输入回文...”,然后是文本。我已经尝试过使用 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"); }
}
I'm creating a program that checks if a word or phrase is a palindrome. I have the actual "palindrome tester" figured out. What I'm stuck with is where and what to place in my code to have the console read out "Enter palindrome..." and then text. I've tried with IO but it doesnt work out right. Also, how do I create a loop to keep going? This code only allows one at a time `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"); }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要阅读文本,您需要使用 Scanner 类,例如:
在实际执行回文检查之前应用此概念,然后在前面进行排序。
至于循环以允许多次检查,您可以执行诸如提供关键字(例如“exit”)之类的操作,然后执行类似的操作:
显然,将相关代码放在中间。
To read in the text, you'll need to make use of the Scanner class, for example:
Apply this concept before you actually do a palindrome check, and you're sorted on that front.
As for looping over to allow multiple checks, you can do something like provide a keyword (such as "exit") and then do something like:
With your relevant code in the middle, obviously.
这不是一个真正的答案,因为它已经给出了(因此是 CW),但我无法抗拒(重新)编写
isPalindrome()
方法;)Not a real answer since it's already given (hence CW), but I couldn't resist (re)writing the
isPalindrome()
method ;)另一个常见的习惯用法是将测试包装在一个方法中:
然后过滤标准输入,为每一行调用 isPalindrome():
这使得检查单行
或整个文件变得容易:
Another common idiom is to wrap your test in a method:
Then filter standard input, calling
isPalindrome()
for each line:This makes it easy to check a single line:
or a whole file: