[英]Given a A string , print Yes if it is a palindrome, print No otherwise
I want to check if the user input is a palindrome or not.我想检查用户输入是否是回文。 But this is not working as expected.
但这并没有按预期工作。 Please help.
请帮忙。
The code I tried:我试过的代码:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
for (int i=0; i<A.length()/2; i++){
if(A.charAt(i)==A.charAt(A.length()-i-1)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
You're printing "Yes" for every character that has the same character at the opposite end of the String and "No" if not.您正在为字符串另一端具有相同字符的每个字符打印“是”,如果不是,则打印“否”。 Modify your loop to return a boolean that tells whether the String is a palindrome or not and then print it at the end like so:
修改你的循环以返回一个 boolean ,它告诉字符串是否是回文,然后在最后打印它,如下所示:
boolean isPalindrome = true;
for (int i=0; i<A.length()/2; i++){
if(!A.charAt(i)==A.charAt(A.length()-i-1)){
isPalindrome = false;
}
}
if(isPalindome){
System.out.println("Yes");
} else {
System.out.println("No");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
String reverse = new StringBuffer(A).reverse().toString();
if (A.equals(reverse))
System.out.println("Yes");
else
System.out.println("No");
}
int end = A.length()-1;
int i=0;
boolean isPol = true;
while (i<=end){
if (A.charAt(i)!=A.charAt(end))
isPol = false;
i++;
end--;
}
if (isPol == true) System.out.println("Yes");
else System.out.println("No");
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
/* Enter your code here. Print output to STDOUT. */
String reverse = "";
int length = A.length();
for (int i=length-1;i>=0;i--){
reverse = reverse + A.charAt(i);
}
boolean ans = A.equals(reverse);
if (ans) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
import java.util.Scanner;
public class test {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String A=sc.nextLine();
String temp="";
for(int i=A.length()-1;i>=0;i--){
temp = temp + A.charAt(i);
}
if(A.equals(temp)){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.