这段代码中的逻辑错误是什么。在这个非回文中也显示回文,如“java”不是回文,但代码显示回文
package stringbuffer;
import java.util.Scanner;
public class Task1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer sbuffer = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
sbuffer.append(input.nextLine());
StringBuffer sbuffer1=new StringBuffer();
sbuffer1=sbuffer.reverse();
System.out.println(sbuffer1);
if(sbuffer1.equals(sbuffer)){
System.out.println("palindrome");
}
else{
System.out.println("not palindrome");
}
input.close();
}
}
答案 0 :(得分:0)
如评论中所建议我修改了您的代码,这将正常工作
package stringbuffer;
import java.util.Scanner;
public class Task1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer sbuffer = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
sbuffer.append(input.nextLine());
String actual = sbuffer.toString();
sbuffer.reverse();
System.out.println(sbuffer);
if(sbuffer.toString().equals(actual)){
System.out.println("palindrome");
}
else{
System.out.println("not palindrome");
}
input.close();
}
答案 1 :(得分:0)
逻辑错误,因为您正在使用引用。 试试这个:
package stringbuffer;
import java.util.Scanner;
public class Task1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer sbuffer = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
sbuffer.append(input.nextLine());
String original = sbuffer.toString();
sbuffer.reverse();
if(original.equals(sbuffer.toString()){
System.out.println("palindrome");
}
else{
System.out.println("not palindrome");
}
input.close();
}
}
答案 2 :(得分:0)
使用此代码检查句子中有多少回文。 这不使用任何预定义的方法来反转。
import java.io.*;
class String_Pallindrome
{
public static void main()throws IOException
{
DataInputStream br= new DataInputStream(System.in);
String word="",str,word1="";
char c,ch;
int i,j,pc=0;
System.out.println("Enter the Sentence");
str=br.readLine();
System.out.print("The Pallindrome words are :- ");
for(i=0;i<str.length();i++)
{
c=str.charAt(i);
if(c==' ')
{
for(j=0;j<word.length();j++)
{
ch=word.charAt(j);
word1=ch+word1;
}
if(word1.equalsIgnoreCase(word)==true)
pc++;
word1="";word="";
}
else
word+=c;
}
System.out.println();
System.out.println("Number of Pallindrome word= "+pc);
}
}
答案 3 :(得分:0)
使用此代码检查字符串是palindrome还是not-palindrome
Scanner sc = new Scanner(System.in);
System.out.print("Enter You String : ");
String string = sc.nextLine();
String reverse = new StringBuffer(string).reverse().toString();
if(string.equals(reverse)){
System.out.println("palindrome");
}
else{
System.out.println("not palindrome");
}