0

ユーザーから文字列を取得し、それが回文であるかどうかをテストするプログラムを作成する必要があります。これはネストされたループで行う必要があります。答えを返すメソッドを作成できません。また、ユーザーが空の行に入るまで文字列入力を受け入れてテストし続ける必要があります。空の行に入ると、プログラムは「さようなら」を出力して終了します。私が問題を抱えているのは、2つの可能な入力ポイント(回文であるがそうではない)の後に入力を受け入れ、ループで新しい入力を使用して、毎回適切な行を出力するようにプログラムを取得することです。

出力は次のようになります。

文字列を入力してください:rotor

ローターは回文です。

文字列を入力してください:ミイラ

ミイラは回文ではありません。

文字列を入力してください:

空の行が読み取られました。さようなら。

これは私がこれまでに持っているものであり、各入力をテストして正しいステートメントを返しますが、入力が空の場合は何もしません。

System.out.print("Enter a string: ");
String input = in.next();
if (input.length() > 0) {
     int x = 0;
     int y = input.length()-1;
     while (x < y) {
          if (input.charAt(x) == input.charAt(y)) {
               x++;
               y--;
          }
          else {
               System.out.println(input + " is NOT a palindrome.");
               System.out.println("Enter a string: ");
               input = in.next();
          }
          System.out.println(input + " is a palindrome.");
          System.out.println("Enter a string: ");
          input = in.next();
     }
}
else {
     System.out.print("Empty line read - Goodbye!");
}

何かご意見は?これは宿題ですが、私は手がかりや私が見る必要のあるものほど答えを探していません。

4

1 に答える 1

2

OK, Since it's your homework, I'll just give you a brief description about how you can proceed: -

  • Since you need to continously take user input, so probably you would be needing some kind of loop, that can continue until a condition is reached (You can think, what loop constrct will go here)

  • Secondly, you need to ask user when he want to quit, so you need to specify a exit condition..

  • Third, for checking for palindrome, you need to check a string with it's reverse..

  • Since you have to use nested loop, you can use length of the string entered, in your loop condition.. Remember, you just need to loop till half the length. Why, you need to find out.. then, compare first character with last, then 2nd character with 2nd last.. until characters are matching.. You need to find out when you will exit the loop..

I think this much information will get you started..

Also one more thing.. May be you are restricted with the use of any method, but it is absolutely bad idea and ugly design to do everything in main().. In fact any of your method should not do more than one task.. And especially your main() method should ideally be just 4 - 5 lines long..

When coding a method, if you think this part is something different, move it outside to another method, and invoke it.. This is the way you should code..

于 2012-10-02T21:06:01.283 に答える