2017-11-17 9 views
-1

私は、ユーザーが入力として与える単語を操作するこのプログラムを作成しました。最初の文字を単語の最後まで移動させて残りの単語を綴ります元の単語と新しい単語が同じかどうかを確認します。これは、ユーザーが選択した単語として「quit」という単語を入力するまで実行されるように設計されています。私は以前のものをチェックした後に新しい単語を尋ねるためにループバックする代わりに、大部分のコードが機能するように管理しました。私が現在持っているコードは以下の通りです:プログラムはバック開始までループするたびにそのチェックを単語しない理由ループプログラムを終了した後の開始点に戻す

package uploadTask9_wordPlay; 

import java.util.Scanner; 

public class wordPlay { 

    public static void main(String[] args) { 
     // creates scanner object to get a name from the user input 
     Scanner userInput = new Scanner(System.in); 

      System.out.println("Enter a name to be tested, or 'quit' to exit 
program: "); 
      // stores the user input into string testedName 
      String testedName = userInput.nextLine(); 

      // if the user input is "quit", program exits 
      if (testedName.equals("quit")) { 
       System.out.println("Thanks for using the program"); 
       System.exit(0); 
      } 

      // else, do the rest of the code with the given word 
      else { 

       while (testedName != "quit") { 

      // takes first character from userInput 
      char firstLetter = testedName.charAt(0); 

      // removes first character from testedName 
      StringBuilder removeChar = new StringBuilder(testedName); 
      removeChar.deleteCharAt(0); 

      // adds first character of testedName to the end of removeChar 
      String newString = removeChar.toString() + firstLetter; 

      // prints newString backwards 
      String reverseWord = new 
StringBuffer(newString).reverse().toString(); 

      // if statement - far simpler way to carry this task out than loops 
      // if statement to check if the words are the same 
      if (testedName.equals(reverseWord)) { 
       System.out.println(testedName + " is the same as " + reverseWord); } 

      else { 
       System.out.println(testedName + " is not the same as " + reverseWord); } 

     } 
    }  
} 
} 

誰でも知っていますか?

+0

を。 'testedName!=" quit "'が間違っています。 '!testedName.equals(" quit ")'を使用してください。しかし、あなたの 'else'ステートメントにあるように無限ループが恐れられ、値は変更されません。 – notyou

+0

@ Hovercraft Eelsの満員 - それは正確には問題そのものではありません。ループの配置方法のためにループバックしません。 – notyou

+0

うわー、これは何の印がついたものでもないのです... はい、1つの間違いは、文字列を!=と比較しているということです、それはうまくいかず、他の間違いはあなたが得ていることですループの前にユーザーが入力する必要があります。 – 5tingr4y

答えて

0

このような文字列を比較しないでください:

testedName != "quit" 

は、この操作を行います。これはおそらく、全体として問題を解決しないであろうけれども

!testedName.equals("quit") 
+1

「!」を好むと恐ろしいNPEを避けるために「.equals(testedName)」を終了します。 – Bathsheba