2016-01-21 11 views
16

何らかの理由でmy forループが自分のCapitalizeFirstSentenceメソッドで終了していません。私はその行にブレークポイントを設定し、条件(i!= -1)は満たされていないので、ループは終了しますが、終了しません!Java forループがコード内で終了していません

これは、条件に(i> 0)を使用すると機能します。

私はここで何が起こっているのか分かりません。

import javax.swing.JOptionPane; 

public class SentenceCapitalizer { 


    //Main Method 
    public static void main(String[] args) { 
     String input; //creates a String to hold keyboard input 

     //Prompt the user to enter a String using JOptionPane and set it equal to input 
     input = JOptionPane.showInputDialog("Enter a string. "); 

     //Display the new String with the first letter of each sentenced capitalized 
     JOptionPane.showMessageDialog(null, CapitalizeFirstSentence(input)); 

     //Exit the program 
     System.exit(0); 
    } 


    //Capitalize first letter of each sentence 
    public static String CapitalizeFirstSentence(String in) 
    { 
     //Creates a StringBuilder object initiralized to the String argument "in" 
     StringBuilder temp = new StringBuilder(in); 

     //Capitalize first letter of the string if string length is > 0 
     if (temp.length() > 0) 
     { 
      temp.setCharAt(0, Character.toUpperCase(temp.charAt(0))); 
     } 

     //sets i equal to index of the space, 
     //keep capitalizing first letters of each sentence (loops each time it capitlizes a letter) 
     //until very end of the String 
     for (int i = temp.indexOf(". ")+1; i != -1; i++) 
     { 
      //Checks for extra spaces and moves index to first character of next sentence 
      while (i < temp.length() && temp.charAt(i) == ' ') 
      { 
       i++; 
      } 

      //Capitalize character 
      temp.setCharAt(i, Character.toUpperCase(temp.charAt(i))); 

      //Index the end of the sentence 
      i = temp.indexOf(". ", i); 
     } 

     //Convert temp to a String and return our new first-sentenced-capitalized String 
     return temp.toString(); 

    } 

} 
+0

'in'文字列変数で指定した値は何ですか? – SMA

+1

[デバッガとはどのようなものですか?また、どのように問題を診断するのに役立ちますか?(http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me -Diagnose-problems) – Raedwald

答えて

24

まず、forループ内のループ制御変数を変更するのは良い考えではありません。そのようなコードを読んで理解することは非常に難しく、エラーが発生しやすくなります。あなたの例に今

、:

for (int i = temp.indexOf(". ")+1; i != -1; i++) 

これが意味:

  • を初期化itemp.indexOf(". ")+1に、常に> = 0
  • ある各繰り返した後であればi == -1
  • を終了し、増分i by 1

だから:初期化は常に各反復> = 0

  • を返すため、サイクル開始時

    • 終了しません、ループ本体はi = temp.indexOf(". ", i);をセットする、である> = -1
    • 各反復後、> = 0常に、それは条件 i == -1を満たすことはありませんので、を終了することはありません
    • iは1だけインクリメントされるので、今iとして> = 0
    • あろう
  • +0

    ああありがとう!意味あり。 –

    7

    この行:for (int i = temp.indexOf(". ")+1; i != -1; i++) iはのindexOf + 1の結果であると初期化します。 IndexOfはヒットがない場合は-1を返しますが、初期化時に常に1を加算するため、0より小さくなることはありません。

    i > 0を使用すると完全に細かく見えます。

    +2

    これは簡単ではありません - OPはループ内で 'i'を修正しています。 –

    +1

    はい、そうです。あなたの答えはより良いです。 – sfThomas

    関連する問題