2

I have a problem when I compare the new word with the original word. I'm suppose to type in words like "banana" and take the first letter to the end and it should spell it backwards to equal "banana". The two words are equal. And if I type in "dog" it becomes "dgo". But in my code if i type in "banana" it still shows it not equal. Idk what to do.

import java.util.Scanner;
public class Project9 
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String word, afc, newWord;
String s="";

do
    {
    word=keyboard.next().toLowerCase();
    int i =word.length()-1;
    char firstLetter=word.charAt(0);
    afc=word.substring(1);
    newWord= afc+firstLetter;

    for( ; i>=0; )
    {
        s += newWord.charAt(i--);
    } 
    System.out.println(word + "," + s);

        if (s.equals(word))
            System.out.println("Words are equal.");
        else
            System.out.println("Words are not equal.");
    }
while (!(word.equals("quit")));

}
}
4

2 に答える 2

1

問題は、コードが単語を逆に出力することです

for( ; i>=0; )
  System.out.print(newWord.charAt(i--));

しかし、あなたは反転していないバージョンを

newWord.equals(word)

次のようなものが欲しいと思います:

String s = "";
for( ; i>=0; )
  s += newWord.charAt(i--);
System.out.println(s);

if (s.equals(word))
  ...
于 2013-03-09T09:36:28.313 に答える
0

それとは別に バナナアナナブを比較していますが、小さなタスクに対して非常に多くの操作を行っています。文字列を変更するたびに新しい String オブジェクトが作成されるため、文字列操作はお勧めできません。私はあなたの要件に合わせてコードを書きました。何度も操作する必要がある場合、文字配列が文字列よりも優れていることを願っています



public static void main(String [] args)
{
    Scanner keyboard = new Scanner(System.in);
    String word, newWord;
    do  
    {
        word=keyboard.next().toLowerCase();
        int i =word.length()-1;
        char[] ca=new char[i+1];
        ca[0]=word.charAt(0);
        for( int j=1; i>0;j++ )
        {
            ca[j]=word.charAt(i--);
        }
        newWord= new String(ca);

        System.out.println(word+","+newWord);

        if (newWord.equals(word))
            System.out.println("Words are equal.");
        else
            System.out.println("Words are not equal.");
    }
    while (!(word.equals("quit")));
}
于 2013-03-09T10:32:57.663 に答える