0

This is my function

public static String  isPalindrome(String str) {
    String test = "";
    String anotherStirng="";
    for (int i = str.length()-1; i >= 0; i--) {
        test = test + str.charAt(i);
    }
    return anotherStirng = (str.equals(test) ? "yes" : "no");

}

main is here ...

Scanner scanner = new Scanner(System.in);
    int numberOfInput = scanner.nextInt();
    String str ="";
    String result="";
    for (int i=0;i<numberOfInput;i++){
            str = scanner.nextLine();
            result = isPalindrome(str);
            System.out.println(result);

when i enter number of input in the console like 3 or 4, it automatically say "yes" after that its works fine

  • This sounds like a scanner problem, not any other issue with your code. The first call to `Scanner#nextInt()` seems to become an input into the palindrome method. After this, all works as expected. – Tim Biegeleisen Dec 12 '18 at 15:21
  • Replace `int numberOfInput = scanner.nextInt();` with `int numberOfInput = Integer.parseInt(scanner.nextLine());` – forpas Dec 12 '18 at 15:22
  • nextInt doesn't go to the next line ... you have to call nextLine again before teh for loop starts – mettleap Dec 12 '18 at 15:22
  • `nextInt` doesn't consume the newline character, so the first call to `nextLine` returns the empty string, which is indeed a palindrome. Instead of calling `nextInt`, try `int numberOfInputs = Integer.parseInt(scanner.nextLine().strip());` – DodgyCodeException Dec 12 '18 at 15:24
  • #forpas, you are awesome!it now works perfectly – nazmulhyder Dec 12 '18 at 15:50

1 Answers1

3

You forgot "scanner.nextLine();" in your code after reading int value. Explanation why you need this line is Here

    Scanner scanner = new Scanner(System.in);
    int numberOfInput = scanner.nextInt();
    scanner.nextLine();   // ADDED LINE
    String str ="";
    String result="";
    for (int i=0;i<numberOfInput;i++){
            str = scanner.nextLine();
            result = isPalindrome(str);
            System.out.println(result);
    }
Rafał Sokalski
  • 1,570
  • 1
  • 12
  • 25