2014-11-13 3 views
-1

그래서 단어 입력을 확인하여 그것이 회문인지 확인합니다. 내 코드의 오류는 두 문자열 비교와 같습니다. 값을 평등하게 테스트하는 데 .equals()를 사용했지만 작동하지 않습니다. 아이디어가 있으십니까?단어 뒤를 인쇄하는 방법

public class PalindromeTask08 
{ 

public static void main(String[] args) 
{ 
    Scanner in = new Scanner (System.in); 
    int count = 5; 
    int x =0; 

    //loops to input a word 
    do{ 
     System.out.println("input a word"); 
     String answer = in.next(); 
     char[] wordBackwards=new char[answer.length()]; 


     System.out.printf("The lenght of the word inputted is: %s%n", answer.length()); 

     for(int i= answer.length() ; i>0 ; --i) 
     { 

      wordBackwards[x] = answer.charAt(i-1); 
      x++; 
     } 

     x=0; 

     wordBackwards.toString(); 
     System.out.println(wordBackwards); 

     if (answer.equals(wordBackwards)) 
     { 
      System.out.printf("%s is a palindrome", answer); 
      --count; 
      System.out.printf("you have %d more attempts", count); 
     } 
     else 
     { 
      System.out.printf("%s is NOT a palindrome", answer); 
      --count; 
      System.out.printf("you have %d more attempts", count); 

     } 

    }while(count!=0); 
    in.close(); 



    } 

} 
+2

그리고 그게 생성자에서 날짜를 인쇄하는 것과 관련이 있습니까? 적어도 프로그램의 결과를 읽었습니까? 'wordBackwards'의 가치가 기대했던 것과 다르지 않다는 것을 알지 못합니까? –

답변

1

귀하의 문제가

wordBackwards.toString(); 

그것은 다른 어떤 일을하지 않는 당신에게 배열의 주소를 반환한다 :

여기 내 코드입니다.
당신은 그것을 작동하도록 다음과 같이 교체해야합니다

... 
x=0; 
String backWordsString = new String(wordBackwards); 
System.out.println(backWordsString); 
if (answer.equals(backWordsString)) { 
... 

쉬운 방법은이

public class PalindromeTask08 { 
    public static void main(String[] args) { 
     Scanner in = new Scanner (System.in); 
     int count = 5; 
     int x =0; 

     //loops to input a word 
     do { 
      System.out.println("input a word"); 
      String answer = in.next(); 
      if (answer.equals(new StringBuilder(answer).reverse().toString())) { 
       System.out.printf("%s is a palindrome", answer); 
      } else { 
       System.out.printf("%s is NOT a palindrome", answer); 
      } 
      --count; 
      System.out.println("\n you have %d more attempts "+ count); 
     } while(count!=0); 
     in.close(); 
    } 
} 

StringBuilder에 대한 자세한 내용을하는 것입니다 할 수 있습니다.

+0

왜 StringBuilder가 아닌 StringBuffer입니까? –

+1

당신은 정확합니다 StringBuilder가 더 낫습니다! – StackFlowed

+0

빠른 응답을 보내 주셔서 감사합니다. – Crazypigs

관련 문제