我目前正在大学学习一门java课程,我的项目是创建一个输入字符串的回文程序,如果字符串是回文或非回文的话,这个程序不能关闭,因为我的教授希望我通过键盘输入多个字符串。以下是开始代码:
// CSCI 200 Program 2
import java.util.*;
public class Program2
{
//
// method: isPalindrome
// pre-conditions: a string is passed in
// post-conditions: return true if the string is a palindrome otherwise return false
//
public static Boolean isPalindrome(String s)
{
//Palindrome Code -- this requires a return statement, but i'm not sure
//what.
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("String: ");
String word = s.nextLine();
//
// keep reading words until the word QUIT is read in
//
while (!word.equals("QUIT"))
{
//
// call the isPalindrome method passing it the word
// based on what this method returns (true or false) output a message
//
if (isPalindrome(word))
System.out.println("the string [" + word + "] IS a palindrome.");
else
System.out.println("the string [" + word + "] IS NOT a palindrome.");
word = s.nextLine();
}
}
}在isPalindrome方法下,它说它需要一个返回语句,但我不知道它是什么,我已经花了两天的时间尝试不同的代码和返回语句。任何帮助都将不胜感激。
我也做了一个工作回文程序,但我似乎不能让它重复,它只需要一个字符串(例如雷达),说回文,然后退出。
谢谢。
发布于 2020-02-13 06:26:15
isPalindrome方法的返回类型是Boolean,这就是为什么它需要一个类型为Boolean ( true或false )的返回语句。因此,如果给定字符串的相反值等于它的值,那么返回true、else、返回false。下面是工作片段:
public class Program2{
public static Boolean isPalindrome(String string) {
if (null == string)
return false;
String reverse = new StringBuffer(string).reverse().toString();
if (string.equals(reverse))
return true;
return false;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("String: ");
String word = s.nextLine();
while (!word.equals("QUIT")) {
if (isPalindrome(word)) {
System.out.println("The string [" + word + "] IS a palindrome.");
} else {
System.out.println("The string [" + word + "] IS NOT a palindrome.");
}
System.out.println("String: ");
word = s.nextLine();
}
s.close();
}
}输出:
String:
test
The string [test] IS NOT a palindrome.
String:
madam
The string [madam] IS a palindrome.
String:
QUIT发布于 2020-02-13 06:11:23
在检查回文单词之前,我做了一个类,看看这是否有帮助。
class reverse
{
private String tmp="";
private int i;
private boolean loop = true;
public void reverseMe(String msg)
{
if(msg.equals("xxx"))
{
loop = false;
}
else
{
i = msg.length()-1;
do
{
tmp += msg.charAt(i);
i--;
}while(i>=0);
if(tmp.equals(msg))
{
System.out.println("Palindrome");
//loop = true;
tmp = "";
}
else
{
System.out.println("Not a Palindrome!");
//loop = true;
tmp = "";
}
}
}
public boolean getLoop()
{
return loop;
}
}发布于 2020-02-13 06:15:44
您需要为isPalindrome方法添加实现,下面是相同的实现-
public static Boolean isPalindrome(String s) {
int leftCount = 0;
int rightCount = s.length() - 1;
int lenght = (s.length() - 1) / 2;
boolean isPalindrome = true;
while(leftCount < lenght ) {
if(s.charAt(leftCount++) != s.charAt(rightCount--)) {
isPalindrome = false;
break;
}
}
return isPalindrome;
}我建议您先阅读Java教程,然后尝试解决逻辑问题,然后尝试为isPalindrome方法实现您自己的逻辑,也许您的解决方案会比我的更好。
https://stackoverflow.com/questions/60201361
复制相似问题